【问题标题】:Transfering int between activities does not work correctly在活动之间传输 int 无法正常工作
【发布时间】:2017-01-15 17:02:32
【问题描述】:

我需要在 2 个活动之间传输 User 和 int,当单击列表视图中的项目时会发生这种情况, 活动一:

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

位置默认是用户单击的项目的编号,log.d 确实显示了当前位置,但是当我尝试在活动 2 中获取该 Int 时,它始终为 0。

在活动 2 中:

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

这个 log.d 总是显示 0。 用户转移得很好。

编辑

我发现它与清单中的 android:launchMode="singleTask" 有关,由于某种原因,活动打开了两次,一次打开良好,一次打开,额外的“serverNum”等于 0,有关如何解决此问题的任何建议?

【问题讨论】:

  • 确定你的名字没有拼写错误?最好使用常量来避免这种可能性。
  • 很确定有几个原因,1 我没有得到空值,日志显示“D/Server Number: 0”,我检查了 10 次它不是通过应对和粘贴的错字

标签: java android android-studio android-intent extras


【解决方案1】:

在你的活动 2 中试试这个。

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

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

【讨论】:

  • 日志仍然显示“D/ServerNumber: 0”
  • 位置的数据类型是int?
  • 是的,我发现它与清单中的 android:launchMode="singleTask" 有关,由于某种原因,活动打开了两次,一个打开良好,一个出于某种原因打开额外的“serverNum”等于 0,有什么建议可以解决这个问题吗?
  • 我不明白你的问题。也许你可以编辑你的帖子。
【解决方案2】:

尝试覆盖方法并在那里检查值

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

}

【讨论】:

    【解决方案3】:

    你应该摆脱android:launchMode="singleTask"。原因是这只创建了一个活动实例。一旦你回到它,它会将额外的重置为 0。在这里你可以阅读启动类型:https://inthecheesefactory.com/blog/understand-android-activity-launchmode/en

    【讨论】:

      猜你喜欢
      • 2018-08-26
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      相关资源
      最近更新 更多