我的應用使用LocationServices來請求位置更新。它通過PendingIntent將結果發送到接收器。在的onReceive()一個LocationResult從意圖,這產生一個位置,其隨後在緯度和來表示LNG,有待進一步用於提取。聽起來不錯,對吧?從onReceive()中的LocationResult獲取位置
那麼,應用程序開始崩潰與空指針異常。
我調查使用調試器,發現我在上面所描述的三個行代碼執行精細,但隨後,代替進行到下面的代碼行,執行在某種程度上涉及再次回到第一的三行,從意圖中提取LocationResult。現在原來是空的,並在NullPointerException,作爲墜毀在以下行位置結果假定不爲空。
我不知道爲什麼會發生這種情況。任何指針,請? (很抱歉的雙關語)
這裏是我的代碼:
public class MyLocationUpdateReceiver extends BroadcastReceiver {
private static final String TAG = "MyLocationUpdateRcvr";
// empty constructor
public MyLocationUpdateReceiver(){}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"onReceive update");
// extract locationResult from intent received from Update Request
LocationResult locationResult = LocationResult.extractResult(intent);
double locationLat = locationResult.getLastLocation().getLatitude();
double locationLng = locationResult.getLastLocation().getLongitude();
// send the Lat and Lng of new location to MapActivity via intent
Intent mIntent = new Intent(context.getApplicationContext(),
MapActivity.class);
mIntent.putExtra("New_Lat", locationLat);
mIntent.putExtra("New_Lng", locationLng);
mIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
這裏是第一次through.Note的LocationResult不是空的屏幕截圖。
不過在第一次圓...
並在第二次輪...
可能是您的意圖'null'。 – Piyush
第一次不是空的 –