Transfering int between activities does not work correctly

68 views Asked by At

I need to transfer User and int between 2 activities, this happens when clicked on item in listview, Activity 1:

Intent intent = new Intent(GameActivity.this,ServerActivity.class);
intent.putExtra("serverNum",position);
intent.putExtra("currentUser",currentUser);
Log.d("position", position + "");
startActivity(intent);
finish();

the position is by defult the number of the item that the user clicked on, The log.d shows the currect position indeed, but when I try to get that Int in activity 2 its always 0.

In activity 2:

Log.d("Server Number",getIntent().getExtras().getInt("serverNum")+"");

this log.d always shows 0. the user transfers well though.

EDIT

I found out it has something to do with android:launchMode="singleTask" in the manifest, for some reason the activity opens twice, one opens well and one for some reason opens with the extra "serverNum" equals to 0, any suggestions on how to fix this?

3

There are 3 answers

4
John Joe On

Try this in your Activity 2.

int id=getIntent().getIntExtra("serverNum", 0);

Log.d("ServerNumber",id+"");
0
amodkanthe On

Try overriding method and check value there as well

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
int id=intent.getIntExtra("serverNum", 0);
Log.d("ServerNumber",id+"");
setIntent(intent);

}
0
BlackHatSamurai On

You should get rid of android:launchMode="singleTask". The reason is that this creates only one instance of the activity. Once you go back to it, it resets the extra to 0. Here you can read up on launch types: https://inthecheesefactory.com/blog/understand-android-activity-launchmode/en