2012-01-14 89 views
0

編輯:答案不是調用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。

我已經瀏覽了許多類似的答案,但沒有爲我工作。

回答

1

//不需要創建爲

CalledActivity calledActivity = new CalledActivity(); //comment this line 

//任何對象做到這一點

intent.startActivityForResult(intent, CALLED_ACTIVITY_CODE); 
+1

那麼血腥簡單又那麼多時間浪費了..謝謝:) – 2012-01-14 10:47:54

+0

您的代碼會拋出一個編譯錯誤:「方法startActivityForResult(Intent,int)未定義類型意圖」 – 2012-10-21 00:59:33

1
 Intent intent = new Intent(CallingActivity.this, CalledActivity.class); 
     startActivityForResult(intent, CALLED_ACTIVITY_CODE); 
+0

的確應該調用調用者的上下文而不是意圖對象。 – 2012-01-14 16:12:23

相關問題