当在myFragment类中调用onLocationChanged时,我得到空指针异常,该类扩展了片段并实现了LocationListener
java.lang.NullPointerException
at com.mypackage.MyFragment.onLocationChanged(myFragment.java:616)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:237)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:170)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:186)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
at dalvik.system.NativeStart.main(Native Method)
这是我使用的代码:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
locationManager = (LocationManager) getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
if (provider !=null)
{
location = locationManager.getLastKnownLocation(provider);
if(location!=null)
{
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 0, 0,this);
}
navigatorBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(provider!=null)
{
showNav(locationLat,locationLong,destinationLat,destinationLong);
}
else
{
//show error msg
}
}});
}
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
if (provider !=null)
{
// Getting latitude of the current location
locationLat= location.getLatitude();
// Getting longitude of the current location
locationLong= location.getLongitude();
}
}
public void showNav(double fromLat, double fromLong, double toLat, double toLong)
{
Uri uri =Uri.parse("http://maps.google.com/maps?&saddr="+fromLat+","+fromLong+"&daddr="+toLat+","+toLong);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
片段正常打开并且工作正常,但有时它会崩溃,给出空指针..可能有什么问题?可能是因为GPS吗?我怎样才能避免这样的错误?
将onLocationChanged
更改为:
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (provider != null) {
// Getting latitude of the current location
locationLat = location.getLatitude();
// Getting longitude of the current location
locationLong = location.getLongitude();
}
}
使用onLocationChanged
方法参数arg0
获取当前纬度,经度。