在Android中使用意图传递bundle时,主活动获取bundle失败

6

我遇到的问题是我的应用在启动时总是崩溃。我有两个活动:Activity A 和 Activity B。应用在 Activity A 上启动,但我已经在 Activity B 中创建了一个 bundle 并将其发送到 Activity A。所以当它启动时,bundle 是空的或者为 null,导致崩溃。我该如何解决这个问题?谢谢。

以下是在 Activity A(启动 Activity)中 onCreate() 方法中的代码:

    Bundle extras = getIntent().getExtras();
    Title = extras.getString("Title");
    Description = extras.getString("Description");
    Price = extras.getString("Price");
    Availability = extras.getString("Availability");

接下来是我在B活动中创建bundle的过程

     Intent intent = new Intent(B.this, A.class);
                Bundle extras = new Bundle();
                extras.putString("Title", PostTitle);
                extras.putString("Description", PostDescription);
                extras.putString("Price", PostPrice);
                extras.putString("Availability", PostAvail);
                intent.putExtras(extras);
                startActivity(intent);

请发布你的代码。 - karimkhan
可能是如何在Android上从意图中获取额外数据?的重复问题。 - Zar E Ahmer
1个回答

11

我建议以下做法:

A. 使用 Intent 中的 Bundle:

Intent pIntent = new Intent(this, JustaClass.class);
Bundle extras = pIntent.getExtras();
extras.putString(key, value); 

创建一个新的Bundle:
Intent pIntent = new Intent(this, JustaClass.class);
Bundle pBundle = new Bundle();
pBundle.putString(key, value);
mIntent.putExtras(pBundle);

C. 使用 Intent 的 putExtra() 方法:

Intent pIntent = new Intent(this, JustaClass.class);
pIntent.putExtra(key, value);

最后在启动的Activity中,您可以通过以下方式读取它们:

String value = getIntent().getExtras().getString(key)

我刚刚用字符串作为传递的例子,我指的是BundleIntent


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