Senki Sem
Senki Sem

Reputation: 131

How to properly use getIntExtra?

I'am trying to pass an integer between two activities.

Activity1:

Intent intent = new Intent(this, Activity2.class);
int num1=40;
intent.putExtra("num1", num1);
startActivity(intent);

Activity2:

Intent intent = getIntent();
int num = intent.getIntExtra("num1", 1);
TextView tv = (TextView) findViewById(R.id.tb_01);
tv.setText(num);

When I start the app, and press the button which starts the method(1. codeblock) it crashes saying: "unfortunately, the program stopped." It works fine when I send strings.

Upvotes: 0

Views: 2485

Answers (2)

323go
323go

Reputation: 14274

You will need to change

tv.setText(num);

to

tv.setText(String.valueOf(num));

TextView.setText(int) will set the text of a resource by integer id, which would more than likely fail, as your num wouldn't have a corresponding resource.

Upvotes: 3

tyczj
tyczj

Reputation: 73763

without a stacktrace this is only a guess but i bet this is the problem

tv.setText(num);

here you are trying to use the number as a resource ID which will not exist so if you want to display the number as text in your text view you need to do

tv.setText(String.valueOf(num))

that will give you a string of the number you passed

Upvotes: 4

Related Questions