How to Get Current Location Inside Android Fragment?
Last Updated :
20 Mar, 2022
A Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layouts for landscape and portrait orientation on a smartphone. The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design.
In this article, we are going to implement an application in which we can get the coordinates of our current location. We will see that who we can get that current location in Fragment.
What we are going to build in this article?
Here is a sample video of what we are going to build in this article. Note that we are going to implement this project using Java language.
Step by Step Implementation
Step 1. Create a New Project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- Name the application at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2. Adding required dependency
Navigate to Gradle Scripts > gradle.scripts(module) and add the following dependency to it
implementation 'com.google.android.gms:play-services-location:17.0.0'
Step 3. Adding required permissions
Navigate to the AndroidManifest.xml file and add the following piece of code to it-
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Step 4. Working on XML files
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame_layout"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Navigate to app > right-click > new > fragment > blank fragment and name it as MainFragment. Use the following code in fargment_main.xml file-
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp"
android:layout_height="match_parent"
tools:context=".MainFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt_location"
android:text="Get Location"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:textSize="32sp"
android:textStyle="bold"
android:textColor="@color/teal_200"
android:layout_marginTop="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_latitude"
android:text="0.0"
android:textSize="24sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude"
android:textSize="32sp"
android:textStyle="bold"
android:textColor="@color/teal_200"
android:layout_marginTop="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_longitude"
android:text="0.0"
android:textSize="24sp"/>
</LinearLayout>
Step 5. Working on Java files
Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.
Java
package com.example.currentloactioninfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize fragment
Fragment fragment= new MainFragment();
// open fragment
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_layout,fragment)
.commit();
}
}
Navigate to the MainFragment.java file and use the following code in it. Comments are added to the code to have a better understanding.
Java
package com.example.currentloactioninfragment;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.PackageManagerCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MainFragment extends Fragment {
// Initialize variables
Button btLocation;
TextView tvLatitude, tvLongitude;
FusedLocationProviderClient client;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
// Initialize view
View view = inflater.inflate(R.layout.fragment_main,
container, false);
// Assign variable
btLocation = view.findViewById(R.id.bt_location);
tvLatitude = view.findViewById(R.id.tv_latitude);
tvLongitude = view.findViewById(R.id.tv_longitude);
// Initialize location client
client = LocationServices
.getFusedLocationProviderClient(
getActivity());
btLocation.setOnClickListener(
new View.OnClickListener() {
@Override public void onClick(View view)
{
// check condition
if (ContextCompat.checkSelfPermission(
getActivity(),
Manifest.permission
.ACCESS_FINE_LOCATION)
== PackageManager
.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(
getActivity(),
Manifest.permission
.ACCESS_COARSE_LOCATION)
== PackageManager
.PERMISSION_GRANTED) {
// When permission is granted
// Call method
getCurrentLocation();
}
else {
// When permission is not granted
// Call method
requestPermissions(
new String[] {
Manifest.permission
.ACCESS_FINE_LOCATION,
Manifest.permission
.ACCESS_COARSE_LOCATION },
100);
}
}
});
// Return view
return view;
}
@Override
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults)
{
super.onRequestPermissionsResult(
requestCode, permissions, grantResults);
// Check condition
if (requestCode == 100 && (grantResults.length > 0)
&& (grantResults[0] + grantResults[1]
== PackageManager.PERMISSION_GRANTED)) {
// When permission are granted
// Call method
getCurrentLocation();
}
else {
// When permission are denied
// Display toast
Toast
.makeText(getActivity(),
"Permission denied",
Toast.LENGTH_SHORT)
.show();
}
}
@SuppressLint("MissingPermission")
private void getCurrentLocation()
{
// Initialize Location manager
LocationManager locationManager
= (LocationManager)getActivity()
.getSystemService(
Context.LOCATION_SERVICE);
// Check condition
if (locationManager.isProviderEnabled(
LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER)) {
// When location service is enabled
// Get last location
client.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
@Override
public void onComplete(
@NonNull Task<Location> task)
{
// Initialize location
Location location
= task.getResult();
// Check condition
if (location != null) {
// When location result is not
// null set latitude
tvLatitude.setText(
String.valueOf(
location
.getLatitude()));
// set longitude
tvLongitude.setText(
String.valueOf(
location
.getLongitude()));
}
else {
// When location result is null
// initialize location request
LocationRequest locationRequest
= new LocationRequest()
.setPriority(
LocationRequest
.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(
1000)
.setNumUpdates(1);
// Initialize location call back
LocationCallback
locationCallback
= new LocationCallback() {
@Override
public void
onLocationResult(
LocationResult
locationResult)
{
// Initialize
// location
Location location1
= locationResult
.getLastLocation();
// Set latitude
tvLatitude.setText(
String.valueOf(
location1
.getLatitude()));
// Set longitude
tvLongitude.setText(
String.valueOf(
location1
.getLongitude()));
}
};
// Request location updates
client.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.myLooper());
}
}
});
}
else {
// When location service is not enabled
// open location setting
startActivity(
new Intent(
Settings
.ACTION_LOCATION_SOURCE_SETTINGS)
.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
}
Here is the final output of our application.
Output:
Similar Reads
How to Get Current Location in Android?
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user's current location in Android. There are two ways to get the current location of
5 min read
How to Create a New Fragment in Android Studio?
Android Studio is the official integrated development environment for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. You can Develop Android App using this. Here, We are going to learn how to create a new Fragment in A
2 min read
How to Get Current Time and Date in Android?
Many times in android applications we have to capture the current date and time within our android application so that we can update our date according to that. In this article, we will take a look at How to get the current Time and Date in our android application. Note: This Android article covere
3 min read
How to get user location in Android
Many apps in Android uses user's locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user's latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query:
6 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI fl
4 min read
How to Implement Current Location Button Feature in Google Maps in Android?
The current location is a feature on Google Maps, that helps us locate the device's position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going t
5 min read
Introduction to Fragments | Android
Fragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
Using Fused Location API to Fetch Current Location in Android
Using Fused Location API to Retrieve Current Location Have you ever seen the movement of taxis on the roads while on their way to your location after booking an Uber cab? There are several apps that make use of some form of location service. The ability to use GPS to update the position is a pretty
7 min read
How to Listen to Orientation Change in Android?
In Android, applications can have orientations of types namely portrait and landscape. By default, every new project when created comes with a portrait orientation. However, this can be changed to landscape or semi. In the case of the semi, both portrait and landscape orientation is supported by the
3 min read
How to Send Data From Activity to Fragment in Android?
Prerequisites:Introduction to Activities in AndroidIntroduction to Fragments in AndroidIn Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interfac
5 min read