简体   繁体   English

在活动之间传输int不能正常工作

[英]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: 我需要在2个活动之间转移User和int,这发生在单击列表视图活动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. 该位置是通过取消用户单击的项目的编号来实现的。log.d确实显示了当前位置,但是当我尝试在活动2中获取该Int时,其始终为0。

In activity 2: 在活动2中:

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

this log.d always shows 0. the user transfers well though. 此log.d始终显示为0。尽管用户传输良好。

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? 我发现它与清单中的android:launchMode =“ singleTask”有关,由于某种原因,该活动打开两次,一个很好打开,一个由于某种原因而打开,且多余的“ serverNum”等于0,关于如何解决这个问题?

Try this in your Activity 2. 在练习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" . 您应该摆脱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 一旦回到它,它将多余的值重置为0。在这里您可以阅读启动类型: https : //inthecheesefactory.com/blog/understand-android-activity-launchmode/en

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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