我有一个处理通知的服务。当我点击通知时,我将Parcelable
对象发送到活动(NotificationActivity):
服务:
Intent destIntent = new Intent (this, NotificationActivity.class);
destIntent.putExtra ("notificationData", new ParcelableObject (mes));
PendingIntent contentIntent = PendingIntent.getActivity (this, 0, destIntent, 0);
NotificationActivity.java :
public class NotificationActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_notification);
// Always NullPointerException
ParcelableObject model = (ParcelableObject) (savedInstanceState.getParcelable ("notificationData"));
TextView content = (TextView)findViewById(R.id.content);
if (model == null) {
content.setText ("NULL");
} else {
content.setText (String.valueOf (model.dump ()));
}
}
}
但是在检索Object时我一直有NullPointerException。
编辑: 按照提供的答案后,我编辑了活动的代码:
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_notification);
}
@Override
protected void onNewIntent (Intent intent) {
super.onNewIntent (intent);
setIntent (intent);
// Code not executed here
// Needed to move it to onResume ()
// since according to the doc it comes after onNewIntent ()
}
@Override
protected void onResume () {
super.onResume ();
ParcelableObject model = (ParcelableObject) (getIntent ().getParcelableExtra ("notificationData"));
Log.v ("MODEL :: ", model.dump().toString()); // NullPointerException
TextView content = (TextView)findViewById(R.id.content);
if (model == null) {
content.setText ("NULL");
} else {
content.setText (String.valueOf (model.dump ()));
}
}
有什么建议吗?谢谢。
答案 0 :(得分:1)
添加到tyczj所说的内容,你应该尝试这样的东西来检查它是否为空:
public class NotificationActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_notification);
// Get from Intent if savedInstanceState is null, otherwise use saved state
ParcelableObject model = (ParcelableObject) (savedInstanceState == null ? getIntent().getParcelableExtra("notificationData") : savedInstanceState.getParcelable("notificationData"));
TextView content = (TextView)findViewById(R.id.content);
if (model == null) content.setText ("NULL");
else content.setText (String.valueOf (model.dump()));
}
}
如上所述,你的onSaveInstance/onRestoreInstance
并不总是被调用,所以依靠这些方法并不是一个好主意。相反,您可能需要考虑在onPause()
中保存数据,并在Activity
恢复时进行恢复。
另外,如果Activity
已经存在且您只是使用新的Intent
打开它,则需要确保在活动中覆盖onNewInent(Intent)
以强制使用它新的Intent's
数据,否则您的新数据将无法访问。为此,只需在onCreate()
方法下方添加:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
这将确保Activity
将使用最新的Intent's
数据。
答案 1 :(得分:0)
保存的实例状态仅在设备旋转时使用,或仅在您的活动暂时暂停的那些行中使用,然后重新创建,以便在启动活动时不执行任何操作。
您需要使用getIntent()
来获取对象