2010-08-03 36 views
0

我有這樣的代碼:意向不提取額外

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。這裏發生了什麼?任何解決這個非常惱人的問題。

回答

4

我認爲你很混淆Activity暫停時保存的狀態和通過Intent發送到Activity的數據。

你想擁有這樣的:

Bundle extras = getIntent().getExtras(); 
id = extras.getLong(TasksDBAdapter.KEY_ID); 

Bundle傳遞給onCreate()是你保存the onSaveInstanceState() method而不是Bundle您添加到您的Intent臨時演員的Bundle

+0

請看我的粗體解釋。 – 2010-08-03 16:45:09

0

您正在以非常錯誤的方式檢索附加信息。替換爲你的第二個代碼片段:

id = getIntent().getLongExtra(TasksDBAdapter.KEY_ID, 0); 
Log.i(TAG, "Id of note = " + id); 

下面是這段代碼會發生什麼:getIntent()返回你在你的第一個代碼段(在Intent這是用來啓動當前活動)創造了Intent。然後,.getLongExtra()返回附加的額外信息。如果沒有發現帶有該標籤和該數據類型(長)的額外信息,則返回0.

savedInstanceState用於在低內存條件下關閉Android系統時關閉應用程序狀態。不要混淆這兩個。