Mohit Deshpande
Mohit Deshpande

Reputation: 55247

Intent not extracting extra

I have this code:

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);
}

And this code that retrieves the extra FROM A DIFFERENT ACTIVITY:

 if (savedInstanceState != null) {
        id = savedInstanceState.getLong(TasksDBAdapter.KEY_ID);
    }
 Log.i(TAG, "Id of note = " + id);

In the first code snippet, Logcat says: The id of the selected note is 2, but in the second code snippet, Logcat says: Id of note = 0. What just happened here? Any solutions to this VERY annoying problem.

Upvotes: 0

Views: 509

Answers (2)

Felix
Felix

Reputation: 89626

You are retrieving the extra in a very wrong way. Replace your second code snippet with:

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

Here's what happens in this code: getIntent() returns the Intent you created in your first code snippet (the Intent that was used to launch the current activity). Then, .getLongExtra() returns the attached extra information. If no extra information with that tag and that data type (long) is found, it will return 0.

savedInstanceState is used for saving your app's state when it is shut down by the Android system under low memory conditions. Don't confuse these two.

Upvotes: 0

David Webb
David Webb

Reputation: 193774

I think you're confusing the state which is saved when an Activity is paused and the data delivered to the Activity via an Intent.

You want to have something like:

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

The Bundle passed to onCreate() is the Bundle you saved with the onSaveInstanceState() method and is not the extras Bundle you added to your Intent.

Upvotes: 4

Related Questions