android - 在 Intent 中设置后 Bundle 为空

标签 android android-intent null bundle

我知道有这样的问题: android-intent-bundle-always-nullintent-bundle-returns-null-every-time但没有正确答案。

在我的 Activity 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(Activity 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 包总是空的。我调试了它,Intent (intent = getIntent()) 将所有字段设置为 null,除了一个指示这是什么类的字段 (MapViewActivity)。

我还尝试通过 intent.putExtras(b) 放置 bundle ,效果相同。 intent.putExtra("asdf", true) 仅用于调试 - 我也无法获取此数据(因为 getIntent() 几乎所有字段都设置为空) .

编辑

以下答案正确且有效。这是我的错。我没有正确地将我的包传递给新的 Intent 。

最佳答案

我不确定“信息”的用途,但我建议在涉及其他数据对象之前先将数据从一个 Activity 传递到另一个 Activity 。

Activity 1

    Intent intent = new Intent(Activity1.this, Activity2.class);
    intent.putExtra("asdf", true);
    info.write(intent);
    startActivity(intent);

Activity 2

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

    }

关于android - 在 Intent 中设置后 Bundle 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10107915/

相关文章:

android - 从广播接收器发送 Intent 并附加到 Activity (服务问题)

android - 无法启动 uiautomatorviewer

android - 通过 Intent 传递数据

java - Spring 服务应该是 null 安全的吗?

java - @Value - 始终为空

安卓初学者 :how to detect specific position on imageview in android

Android 模拟器 SDK 无法访问互联网 - 网页不可用。 DNS 无法解析; URL 的 IP 地址有效

SQL:field = other_field 即使它们相同(NULL 值)也返回 false

android.R.id.empty 在 Xoom/Honeycomb 中损坏了吗?

android - Room 中的主键应该是 Int 还是 Long?