简体   繁体   中英

Transfering int between activities does not work correctly

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?

Try this in your Activity 2.

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

Log.d("ServerNumber",id+"");

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);

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM