位置 API - 处理 NullPointerException
Location API - Handling NullPointerException
在 运行 我的应用程序运行一段时间后,我得到一个 NullPointerException
当在下面的代码中调用 Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
时,我想了解如何处理这个异常以防止它在将来崩溃我的代码。
public class LocationIntentService extends IntentService {
public LocationIntentService() {
super("LocationIntentService");
}
private String TAG = this.getClass().getSimpleName();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if (location != null) {
Log.i(TAG, "Location: " + location.getLatitude() + "," + location.getLongitude());
Intent LocationIntent = new Intent("com.xyz.abc.LOCATION_DATA");
LocationIntent.putExtra("lat", location.getLatitude());
LocationIntent.putExtra("lon", location.getLongitude());
getApplicationContext().sendBroadcast(intent);
sendBroadcast(LocationIntent);
} else {
Log.e(TAG, "Location returned NULL catching exception");
}
}
}
任何想法都会很棒!
try {
//code
} catch (NullPointerException e) {
e.printStackTrace();
}
在 运行 我的应用程序运行一段时间后,我得到一个 NullPointerException
当在下面的代码中调用 Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
时,我想了解如何处理这个异常以防止它在将来崩溃我的代码。
public class LocationIntentService extends IntentService {
public LocationIntentService() {
super("LocationIntentService");
}
private String TAG = this.getClass().getSimpleName();
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if (location != null) {
Log.i(TAG, "Location: " + location.getLatitude() + "," + location.getLongitude());
Intent LocationIntent = new Intent("com.xyz.abc.LOCATION_DATA");
LocationIntent.putExtra("lat", location.getLatitude());
LocationIntent.putExtra("lon", location.getLongitude());
getApplicationContext().sendBroadcast(intent);
sendBroadcast(LocationIntent);
} else {
Log.e(TAG, "Location returned NULL catching exception");
}
}
}
任何想法都会很棒!
try {
//code
} catch (NullPointerException e) {
e.printStackTrace();
}