Intent's extra is always null

2019-09-06 18:55发布

问题:

I'm trying to pass an int variable to another activity:

From the current activity:

Intent intent = new Intent(getApplicationContext(),PlayActivity.class);
intent.putExtra("position", position);
startActivity(intent);

At PlayActivity.onCreate:

Intent intent = getIntent();
String position = intent.getStringExtra("position");
int index = Integer.parseInt(position);

Problem is, position is always null (and parseInt() throws exception).
Why?

回答1:

There is no string extra to get since it is an int. You should have

Intent intent = getIntent();
int position = intent.getIntExtra("position");

I'm not sure why you are trying to get a String then parse to an int when it is sent as an int, assuming position is an int in your first Activity. If that is not the case then please explain a little better.

Intent Docs