getIntExtra always returns the default value

Viewed 45217

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?

7 Answers

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.

In my case, it was because I created the object with mId member variable declared as string

public class Application {

private String mId;
....
}

intent.putExtra("id", myApplication.getId());

and as such, the Extra is passed as string. simply change your member variable to int, you get the idea ;)

    int sub_menu_id = 0;
    int question_part = 0;

    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            sub_menu_id = -1;
            question_part = -1;
        } else {
            sub_menu_id = extras.getInt("sub_menu_id");
            question_part = extras.getInt("question_part");
        }
    }

    Log.d("DREG", "sub_menu_id: " + sub_menu_id + "\nquestion_part: " + question_part);

In my case, I converted the value inside putExtra to String from Int and Long and while receiving, received it as String only. Can't figure out why but Integer, Long were showing defaultValues while after converting to String it works.

Example :

intent.putExtra("code", response.data?.code.toString())
val code = intent.getStringExtra("code")
Related