編輯:答案不是調用startActivityForResult
對被調用的Activity對象,而是從調用者的上下文中調用它。NullPointerException while嘗試startActivityForResult
這是我的代碼,異常的最後一行:
107 Intent intent = new Intent(CallingActivity.this, CalledActivity.class);
108 CalledActivity calledActivity = new CalledActivity();
109 calledActivity.startActivityForResult(intent, CALLED_ACTIVITY_CODE);
內CallingActivity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(SR.tag,"req=" + requestCode + " res=" + resultCode); //Never getting here
}
清單文件片段:
<activity android:name=".ui.CallingActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ui.CalledActivity"></activity>
例外:
01-14 11:30:14.850: ERROR/AndroidRuntime(1036): FATAL EXCEPTION: main
01-14 11:30:14.850: ERROR/AndroidRuntime(1036): java.lang.NullPointerException
01-14 11:30:14.850: ERROR/AndroidRuntime(1036): at android.app.Activity.startActivityForResult(Activity.java:2833)
01-14 11:30:14.850: ERROR/AndroidRuntime(1036): at com.litvin.app.ui.CallingActivity.onSharedPreferenceChanged(CallingActivity.java:109 )
...
每當我將HOME和LAUNCHER意圖過濾器移動到.ui.CalledActivity
時,它工作正常。當我按下圖標時它會啓動CalledActivity。
我已經瀏覽了許多類似的答案,但沒有爲我工作。
那麼血腥簡單又那麼多時間浪費了..謝謝:) – 2012-01-14 10:47:54
您的代碼會拋出一個編譯錯誤:「方法startActivityForResult(Intent,int)未定義類型意圖」 – 2012-10-21 00:59:33