gpt4 book ai didi

java - 位置 API - 处理 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 11:59:59 25 4
gpt4 key购买 nike

运行我的应用程序一段时间后,当在下面的代码中调用 Location location = Intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED); 时,我得到一个 NullPointerException ,我我试图了解如何处理此异常,以防止它将来使我的代码崩溃。

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();
}

关于java - 位置 API - 处理 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28047190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com