getLastKnownLocation returning null in Android -


i know has been talked many times nothing has helped me fix problem getlastknownlocation returning null.

my activity implement locationlistener:

public class mainactivity extends activity implements     googleplayservicesclient.connectioncallbacks,     googleplayservicesclient.onconnectionfailedlistener, locationlistener { 

i have in oncreate method:

  locationmanager lm = (locationmanager) getsystemservice(location_service);   lm.requestlocationupdates(locationmanager.gps_provider, 0, 0, this); 

and try user location (also in oncreate):

    // getting co-ordinates of users current location     location location = lm             .getlastknownlocation(locationmanager.gps_provider);      if(location != null){         longitude = location.getlongitude();         latitude = location.getlatitude();     } 

i tried then:

@override public void onlocationchanged(location location) {           longitude = location.getlongitude();     latitude = location.getlatitude(); } 

am missing something?

edit: still not working code have tried:

    if (lm.isproviderenabled(locationmanager.gps_provider)) {     while (location == null) {         if (counter > max_time) {            }         else {             try {                  location = lm.getlastknownlocation(locationmanager.gps_provider);                 thread.sleep(1000);             } catch (interruptedexception e) {                 e.printstacktrace();             }             counter += 1000;         }     }     } 

from documentation:

"returns location indicating data last known location fix obtained given provider.

returns last known location provider, or null "

so, there must @ least 1 previous location obtained using supplied provider. receive location, have register updates @ least once using provider , receive actual update. after which, getlastknownlocation return value. if want register locations provided other apps, use location.passive_provider.

hope helps.

edit: commented above, put while loop in iterates 30 seconds , checks every second if location not longer null. need happen @ least once, able use getlastknownlocation, afaik.

edit small, untested example. best put in asynctask i.e. in doinbackground. note, i'm assuming storing location object itself, rather separating out longitude , latitude.:

if (lm.isproviderenabled(locationmanager.gps_provider)) {     long final max_time = 30000;     long counter = 0;     while (location == null) {         if (counter > max_time) {             return false;         }         thread.sleep(1000);         counter += 1000;     } } else {     return false; } 

edit: remember, location updated in onlocationupdate(location location). 1 has updated, have location object not equal null.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -