current location is always null

13,626

Solution 1

pleas check your manifest file.whether have you added those permissions or not.

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

See the updated answer:

protected void showCurrentLocation() 
       {
         geocoder = new Geocoder(this); 
         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 
                    MINIMUM_TIME_BETWEEN_UPDATES, 
                    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                    myLocationListener
            );
         timer = new Timer();
         timer.schedule(new GetLastLocation(),20000);

       }

     class GetLastLocation extends TimerTask {

            @Override
            public void run() {
                timer.cancel();
                locationManager.removeUpdates(locationListener);
                 Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                   System.out.println("loc.."+location);
                   if (location != null) 
                   {
                   String message = String.format("Location \n Longitude: %1$s \n Latitude: %2$s",
                                location.getLongitude(), location.getLatitude());
                       Toast.makeText(ShowActivity.this, message,
                               Toast.LENGTH_LONG).show();
                  //acTextView.setText(message);
                   try {
                          List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
                          for (Address address : addresses) {
                              System.out.println("my location .."+address.getAddressLine(0));
                            acTextView.setText(address.getAddressLine(0));
                          }



                        } catch (IOException e) {
                          Log.e("LocateMe", "Could not get Geocoder data", e);
                        }
                    }
                    else
                    {
                    AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
                    alertbox1.setMessage("No GPS or network ..Signal please fill the location manually!");
                    alertbox1.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) 
                    {}});
                    alertbox1.show();
                    }
                }   
                return;
            }
        }

     /** The location listener. */
        LocationListener myLocationListener = new LocationListener() {

            public void onLocationChanged(Location location) {

            }
            public void onProviderDisabled(String provider) {}
            public void onProviderEnabled(String provider) {}
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        };

Solution 2

when we specify NETWORK_PROVIDER to listen for location updates,

Android system makes use of wi-fi ids or internet access points to determine locations

When there is no internet access, it returns null values

Happened with me too, it doesnt get location from cell towers as expected

read into this: no gprs/no wi-fi location updates

Solution 3

Android 2.3.x SDK (API 9 and 10) emulator has bug with GPS. You should try your code on 2.2 (API 8)

Solution 4

Another reason for getting null back from locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); would be if your network provider was turned off. On my phone this is toggled via Settings -> Location -> Use wireless networks.

EDIT:

You could also try:

LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

to see if the network provider is enabled or

LocationManager.getProviders(true)

to return any enabled providers.

See http://developer.android.com/reference/android/location/LocationManager.htm for more info

Share:
13,626
Nibha Jain
Author by

Nibha Jain

I have over a decade of experience in IT industry as a software developer .I have been able keep up with the ever evolving technology stack in the mobile applications domain. Started out as a J2ME developer moved to Android development in java to android development in kotlin to writing web applications in nodejs.

Updated on June 04, 2022

Comments

  • Nibha Jain
    Nibha Jain almost 2 years

    I am trying to retrieve my current location on the button click in an editbox using gps or network..i have tried all possible methods which i found in tutorials and older posts....but my location is always null.. i am not getting where i am wrong.? i am testing it on real device having network but no internet/gprs...

    this is the code which i am using..i tried the same with GPS_PROVIDER as well ..please help me..

         protected void showCurrentLocation() 
       {
         geocoder = new Geocoder(this); 
         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 
                    MINIMUM_TIME_BETWEEN_UPDATES, 
                    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                    new MyLocationListener()
            );
    
       Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
       System.out.println("loc.."+location);
       if (location != null) 
       {
       String message = String.format("Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude());
           Toast.makeText(ShowActivity.this, message,
                   Toast.LENGTH_LONG).show();
      //acTextView.setText(message);
       try {
              List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
              for (Address address : addresses) {
                  System.out.println("my location .."+address.getAddressLine(0));
                acTextView.setText(address.getAddressLine(0));
              }
    
    
    
            } catch (IOException e) {
              Log.e("LocateMe", "Could not get Geocoder data", e);
            }
        }
        else
        {
        AlertDialog.Builder alertbox1 = new AlertDialog.Builder(this);
        alertbox1.setMessage("No GPS or network ..Signal please fill the location manually!");
        alertbox1.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) 
        {}});
        alertbox1.show();
        }
    
    }   
    

    I am just editing the question instead of asking the new one..because my problem is still related to the same...i didn't change anything in the code and this is working perfectly fine now.....But the issue is when i use the GPS_PROVIDER ,it returns the accurate address along with the value of longitude and latitude..but when i use NETWORK_PROVIDER it returns only the value of longitude and latitude no address...i want to retrieve the full address using NETWORK_PROVIDER because GPS not works indoor ...How can i do that?

    Thanks...!!

  • Nibha Jain
    Nibha Jain over 12 years
    thanks hanry..but this is not working in my case..this code is giving null pointer exception...
  • Chris Knight
    Chris Knight over 12 years
    @jiya - you need to take the System.out.println statements out from your code. There is no console in Android. Replace with Log.d(...). Also, try putting MINIMUM_TIME_BETWEEN_UPDATES to 0 and putting a log statement in your location listener to see what happens when a location update is triggered if the network provider is indeed enabled. E.g. its possible no location has ever been requested by your phone which means it will always be null until one is made.
  • shecodesthings
    shecodesthings over 11 years
    This is one of the links I referenced - code.google.com/p/android/issues/detail?id=13046