Skip to content
Related Articles

Related Articles

How to Get Current Location Inside Android Fragment?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • 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.

Fragments in Android

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: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: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:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!