Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getIntExtra always returns the default value

Tags:

android

I am trying to pass an integer between activities using an intent. The source activity makes the calls info.id is the selected item from a ListView.

Intent intent = new Intent(myActivity.this, newClass.class); 
intent.putExtra("selectedItem", info.id); 
this.startActivity(intent); 

The target activity retrieves the intent using getIntent then calls

int iSelectedItem = intent.getIntExtra("selectedItem", -1); 

iSelectedItem is always -1 instead of the value passed to putExtra. Can someone tell me what I am doing wrong or do I misunderstand the use of intents?

like image 947
oregonduckman Avatar asked Jan 26 '10 04:01

oregonduckman


People also ask

What is getIntExtra default value?

getIntExtra returns only the default value #15596.

How can I use getIntExtra in Android?

int diff = getIntent(). getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY); reads the value that was set for KEY_DIFFICULTY in the intent used to start the activity. Hence, diff now contains the user-selected value (or DIFFICULTY_EASY , if the activity is started through a different intent which did not set KEY_DIFFICULTY ).


2 Answers

The problem is that info.id will be a 'long' and is not converting to an 'int'. Try

long iSelectedItem = intent.getLongExtra("selectedItem", -1)
like image 193
Grant Avatar answered Oct 12 '22 11:10

Grant


I don't find putIntExtra() method. So I ended up with following:

intent.putExtra("jobId", 1);

and

Integer.parseInt(getIntent().getExtras().get("jobId").ToString());

Use try and catch to handle Exceptions.

UPDATE

Later I found that I was passing jobId as a string in putExtra() method, therefore getIntExtra() was always returning the default value.

So @Grant is correct. You must pass an Integer value in putExtra() method to use getIntExtra() method.

like image 26
Vikas Avatar answered Oct 12 '22 12:10

Vikas