It seems a common issue, but i really can't understand why is it happening even though i read ton of simialr issues.
I am playing with a basic location class on a emulator device, i set everything - permissions (FINE and COARSE) , i have set the coordinates in the DDMS i also tried using the telnet and then , but no matter what it always crashes witth nullpointer exception on the line with getlastknownlocation, any ideas whats wrong here ?
public class MainActivity extends Activity implements LocationListener {
private static LocationManager ok;
private Location L;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ok=(LocationManager)this.getSystemService(ok.GPS_PROVIDER);
L=ok.getLastKnownLocation(ok.GPS_PROVIDER);
}
@Override
public void onLocationChanged(Location Loc) {
try {
double latop=Loc.getLatitude();
double longe=Loc.getLongitude();
Log.i("OK", "and"+longe+""+latop);
} catch (NullPointerException e)
{
}
}
getLastKnownLocation()
will return null
in general, if no app has requested a location fix from your desired provider recently.
On the emulator, it seems to take it one step further: you do not get a location unless one has been delivered to the emulator since your app has called requestLocationUpdates()
.
The general pattern for using getLastKnownLocation()
, if you want decent odds of getting an actual Location
, is to use requestLocationUpdates()
and removeLocationUpdates()
to ensure that LocationManager
is actively seeking locations via your chosen provider. Of course, you could also use LocationListener
and onLocationChanged()
, rather than getLastKnownLocation()
, if you so chose.
@CommonsWare's answer is clear. To get not-null on emulator go to Google Maps
application and after that you get some location
There is another option, to create your own provider using locationManager.addTestProvider(); so you can make your own tests.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.