Using intent and bundle for integers in Android

送分小仙女□ 提交于 2019-12-12 03:01:12

问题


Say I wanted to pass data from one activity/class to the other involving an integer data type. Here's what I have for the MainActivity (first) class so far:

@Override
public void onClick(View v) {
    Intent i = new Intent(this, SecondActivity.class);
    final int x = 3;
    i.putExtra("new variable", x);
    startActivity(i);
}

For the receiving class, SecondActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    Bundle i = getIntent().getExtras();
    String value = i.getString("new variable");
    tvResult = (TextView)findViewById(R.id.textViewResult);
    tvResult.setText(value);
}

However, SecondActivity shows up with nothing on the second screen... Could it perhaps be because I need to convert value to an int first?

Thanks!


回答1:


I wanted to pass data from one activity/class to the other involving an integer data type...

x is int but in SecondActivity i.getString is used to get data from Bundle which return String instead of int.

Use Bundle.getInt to get int from Bundle.

int value = i.getInt("new variable");

Also use String.valueOf for showing int in TextView as:

tvResult.setText(String.valueOf(value));


来源:https://stackoverflow.com/questions/35121972/using-intent-and-bundle-for-integers-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!