意向不提取额外
问题描述:
我有这样的代码:意向不提取额外
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(TAG, "The id of the selected note is " + id);
Intent editNote = new Intent(this, TaskEditActivity.class);
editNote.putExtra(TasksDBAdapter.KEY_ID, id);
startActivityForResult(editNote, EDIT_TASK_REQUEST);
}
而这种代码,获取额外从不同的活动:
if (savedInstanceState != null) {
id = savedInstanceState.getLong(TasksDBAdapter.KEY_ID);
}
Log.i(TAG, "Id of note = " + id);
在第一代码片段,logcat的说:The id of the selected note is 2
,但在第二个代码片段中,Logcat说:Id of note = 0
。这里发生了什么?任何解决这个非常恼人的问题。
答
我认为你很混淆Activity
暂停时保存的状态和通过Intent
发送到Activity
的数据。
你想拥有这样的:
Bundle extras = getIntent().getExtras();
id = extras.getLong(TasksDBAdapter.KEY_ID);
的Bundle
传递给onCreate()
是你保存the onSaveInstanceState()
method而不是Bundle
您添加到您的Intent
临时演员的Bundle
。
答
您正在以非常错误的方式检索附加信息。替换为你的第二个代码片段:
id = getIntent().getLongExtra(TasksDBAdapter.KEY_ID, 0);
Log.i(TAG, "Id of note = " + id);
下面是这段代码会发生什么:getIntent()
返回你在你的第一个代码段(在Intent
这是用来启动当前活动)创造了Intent
。然后,.getLongExtra()
返回附加的额外信息。如果没有发现带有该标签和该数据类型(长)的额外信息,则返回0.
savedInstanceState
用于在低内存条件下关闭Android系统时关闭应用程序状态。不要混淆这两个。
请看我的粗体解释。 – 2010-08-03 16:45:09