通过intent在活动之间传递变量会抛出NullPointerException

时间:2018-05-03 17:49:42

标签: android android-intent

为什么会抛出NullPointerException?

在Redeem.java中

int yourInt = 200;
Intent myIntent = new Intent(Redeem.this, MainActivity.class);
myIntent.putExtra("intVariableName", yourInt);
startActivity(myIntent);

在MainActivity.java中

Bundle extras = getIntent().getExtras();
int score = extras.getInt("intVariableName");

3 个答案:

答案 0 :(得分:0)

尝试:

Bundle extras = getIntent().getExtras();
String stringScore = extras.getString("intVariableName");
int score = Integer.parseInt(stringScore);

或者:

int score = intent.getIntExtra("intVariableName", 0);

答案 1 :(得分:0)

你也可以试试这个:

int yourInt = 200;
Intent myIntent = new Intent(Redeem.this, MainActivity.class);
myIntent.putExtra("intVariableName", String.valueOf(yourInt));
startActivity(myIntent);

在MainActivity.java中

  Bundle extras = getIntent().getExtras();
  int score =Integer.parseInt(extras.getString("intVariableName"));

答案 2 :(得分:0)

使用此:

KeyValueConfigurationCollection