编辑:答案不是在被调用的Activity对象上调用startActivityForResult
,而是从调用者的上下文中调用它。
这是我的代码,最后一行的例外:
107 Intent intent = new Intent(CallingActivity.this, CalledActivity.class);
108 CalledActivity calledActivity = new CalledActivity();
109 calledActivity.startActivityForResult(intent, CALLED_ACTIVITY_CODE);
Inside 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。
我在这里看了很多类似的答案,但没有一个适合我。
答案 0 :(得分:1)
//无需为该
创建任何对象CalledActivity calledActivity = new CalledActivity(); //comment this line
//执行此操作
intent.startActivityForResult(intent, CALLED_ACTIVITY_CODE);
答案 1 :(得分:1)
Intent intent = new Intent(CallingActivity.this, CalledActivity.class);
startActivityForResult(intent, CALLED_ACTIVITY_CODE);