【问题标题】:getbundle is null when starting previous activity through intent通过意图启动上一个活动时,getbundle 为空
【发布时间】:2019-02-24 05:00:51
【问题描述】:

我的代码 FirstActivity 和 SecondActivity 中有两个活动。

从 FirstActivity 我开始 SecondActivity 看下面的代码

        Intent intent = new Intent(getBaseContext(), SecondActivity.class);
        intent.putExtra("text", "someValue");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

这工作正常,我可以读取我在 FirstActivity 的 putExtra 中添加的 SecondActivity 中的值。

从 SecondActivity 我有一些复杂的代码,但在某些地方我需要启动 FirstActivity,我通过以下代码来完成

            Intent intent = new Intent(getBaseContext(), FirstActivity);
            Bundle bundle = new Bundle();

            /* tested with both bundle and put extra none of them worked
            */
            bundle.putString("text2", "someOtherString");
            intent.putExtra("text3", "someOtherString");                 
            intent.putExtras(bundle);

            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();

这会启动 FirstActivity,但是当我检查代码时(在 FirstActivity 中)

@Override
protected void onStart() {
    super.onStart();
    Intent intent = getIntent();
    if(intent != null) {
        String string, string2;

        Bundle bundle = intent.getExtras();
        if(bundle != null) {
            string = bundle.getString("text2"); //return empty
        }
        string2 = intent.getStringExtra("text3") //returns empty

    }

}

我不明白为什么它是空的? 我应该用不同的标志开始活动吗?如果是,请解释原因。

【问题讨论】:

  • 请清理您的第二个代码块 - 它有拼写错误或导致您观察到的行为的实际错误(创建意图2?填充意图1?填充意图..)
  • 这是拼写错误。感谢您的观察。固定

标签: android android-activity


【解决方案1】:

你需要在 secondActivity 中有一个接口,并在 firstActivity 中实现它。因为你从第二到第一的逻辑是错误的。

【讨论】:

  • 从第二到第一的逻辑错了是什么意思?为什么需要接口?您是否将其与动作片段通信混合在一起
  • 只要实现接口,你就会看到结果
  • 这是我在这里见过的质量最低的答案之一。什么样的界面?这将解决什么样的问题?活动之间的数据是在包之间发送的,所以我不太明白你的意思。有时没有答案比错误或简短的答案更好
猜你喜欢
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多