Home > Back-end >  How do I get the users current location by java in Android Studio
How do I get the users current location by java in Android Studio

Time:11-25

I am trying to make a marker that displays the users current location, but my app is always crashing. By debugging, I know that "here" which is where i store the users latitude and longtitude is always null throughout the program.

Heres the java code, I am simply trying to get the current location when the activity is created.

package com.example.mobileproject;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
 
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
 
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.maps.model.PlacesSearchResult;
 
import java.io.IOException;
import java.util.List;
import java.util.Locale;
 
public class activity_hospitals extends FragmentActivity implements OnMapReadyCallback {
    Toolbar mytoolbar;
    GoogleMap Gmap;
    FusedLocationProviderClient flsc;
    public LatLng here;
    public double longo, lato;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospitals);
        mytoolbar = (Toolbar) findViewById(R.id.hospitalToolbar);
        mytoolbar.setTitle("Hospitals Near You");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 
        flsc = LocationServices.getFusedLocationProviderClient(this);
        getLastLocation();
        mapFragment.getMapAsync(this);
 
    }
 
    @Override
    public void onMapReady(GoogleMap googleMap) {
        Gmap = googleMap;
        LatLng temp = here;
 
        LatLng here = new LatLng(33.71456158807447, 35.48425016137045);
        Gmap.addMarker(new MarkerOptions().position(here).title("Your Location"));
 
        LatLng placeholder1 = new LatLng(33.66535378588594, 35.420147180348465);
        Gmap.addMarker(new MarkerOptions().position(placeholder1).title("Dr. Monzer al Haj Hospital"));
 
        LatLng placeholder2 = new LatLng(33.76696201016636, 35.48301133270906);
        Gmap.addMarker(new MarkerOptions().position(placeholder2).title("SSH"));
 
        float zoomLevel = 11.0f; //This goes up to 21
        Gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, zoomLevel));
    }
 
 
    public void getLastLocation(){
        /*
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            flsc.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if(location!=null){
                        Geocoder geocoder = new Geocoder(activity_hospitals.this, Locale.getDefault());
                        List<Address> addresses = null;
                        try {
                            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                            Double lat = addresses.get(0).getLatitude(), lon = addresses.get(0).getLongitude();
 
                             here = new LatLng(lat, lon);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
 
 
                    }
                }
            });
        }
        else{
            askPermission();
        }*/
 
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            flsc.getLastLocation().addOnSuccessListener(this, location -> {
                if (location != null) {
 
                    longo = location.getLatitude();
                    lato = location.getLongitude();
                    here = new LatLng(lato, longo);
                }
            });
        } else {
        Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
         }
 
 
    }
 
    private void askPermission() {
        ActivityCompat.requestPermissions(activity_hospitals.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
 
 
        if(requestCode == 100){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getLastLocation();
            }
            else{
                Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
            }
 
        }
 
 
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

I tried several youtube videos that all used the same code. I then tried googling it, but the codes I found didnt work either.

CodePudding user response:

The reason "here" is always null could be because you try to use it before the location actually arrived. Try commenting onMapReady() method, and just print your location inside addOnSuccessListener. If that works, than you just have to find a way how to wait for the location to arrive and then show it on the map.

  • Related