在将Bundle设置到Intent中后,Bundle变为null

9
我知道有类似以下问题: android-intent-bundle-always-nullintent-bundle-returns-null-every-time,但都没有正确的答案。
在我的活动 1中:
public void goToMapView(Info info) {
    Intent intent = new Intent(getApplicationContext(), MapViewActivity.class);
    //intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    intent.putExtra("asdf", true);
    info.write(intent);
    startActivity(intent);
}

在信息技术中:

public void write(Intent intent) {
    Bundle b = new Bundle();
    b.putInt(AppConstants.ID_KEY, id);
    ... //many other attributes
    intent.putExtra(AppConstants.BUNDLE_NAME, b);
}
public static Info read(Bundle bundle) {
    Info info = new Info();
    info.setId(bundle.getInt(AppConstants.ID_KEY));
    ... //many other attributes
    return info;
}

在MapViewActivity(活动2)中:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_view);

    Bundle extras = getIntent().getBundleExtra(AppConstants.BUNDLE_NAME);
    info = Info.read(extras);
    ...
}

问题在于`extras`捆绑包始终为null。我已经进行了调试,Intent(`intent = getIntent()`)除了一个指示这是什么类(MapViewActivity)的字段外,所有字段都设置为null。
我还尝试通过具有相同效果的`intent.putExtras(b)`来放置捆绑包。 `intent.putExtra("asdf", true)`仅用于调试目的-我也无法获取此数据(因为getIntent()几乎将所有字段设置为null)。
编辑
下面的答案是正确且可行的。这是我的错误。我没有正确地传递我的捆绑包到新意图。
2个回答

9
我不确定“Info”是什么,但我建议先完成最基本的从一个活动到另一个活动的数据传递,然后再涉及其他数据对象。
活动1
    Intent intent = new Intent(Activity1.this, Activity2.class);
    intent.putExtra("asdf", true);
    info.write(intent);
    startActivity(intent);

Activity2

    Bundle bundle = getIntent.getExtras();
    if (bundle!=null) {
        if(bundle.containsKey("asdf") {
            boolean asdf = bundle.getBooleanExtra("asdf");
            Log.i("Activity2 Log", "asdf:"+String.valueOf(asdf));
        }
    } else {
        Log.i("Activity2 Log", "asdf is null");

    }

Info类用于聚合我需要的信息。它具有静态的“read”和实例的“write”方法,以提高可读性。最基本的数据传递是通过放置“asdf”来表示,但这并不起作用。你是不是想用getBoolean而不是getBooleanExtra?没有这样的方法。我刚刚检查了你的示例 - 我得到了“asdf为空”。但还是谢谢。 - Xeon
第一行需要是 Bundle bundle = getIntent().getExtras();由于短路,两个 if 语句可以合并为 if (bundle != null && bundle.containsKey("asdf")) { - Scott Jodoin

4

活动1

Intent intent = new Intent(getApplicationContext(), MapViewActivity.class);

        Bundle b = new Bundle();
         b.putBoolean("asdf", true);
         b.putInt(AppConstants.ID_KEY, id);
         intent.putExtras(b);

         startActivity(intent);

活动 2

Bundle extras = getIntent().getExtras();

 boolean bool = extras.getBoolean("asdf");
 int m_int = extras.getInt(AppConstants.ID_KEY,-1);

我已经按照底部问题中所述尝试过了:“我还尝试使用intent.putExtras(b)来放置bundle,但效果相同”。Info类没有任何问题。 - Xeon
以上应该可以正常工作。无论如何,尝试直接在Intent中放入值,例如 intent.putExtra("asdf",false);intent.putExtra(AppConstants.ID_KEY,id); - Ravi1187342

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接