java 在android中通过意图传递包时在主要活动上获取包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34599972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting bundle on Main activity when passing bundles by intent in android
提问by Darian B
So the problem I am having is that my app keeps crashing on launch, I have two activities. Activity A and Activity B. My app launches on Activity A but I have created a bundle in Activity B and I am sending it to Activity A. So when it launches the bundle is empty or null so it crashes, how do i fix this? thanks.
所以我遇到的问题是我的应用程序在启动时一直崩溃,我有两个活动。Activity A 和 Activity B。我的应用程序在 Activity A 上启动,但我在 Activity B 中创建了一个包,我将它发送到 Activity A。所以当它启动时包为空或为空,所以它崩溃了,我该如何解决这个问题?谢谢。
This is in Activity A (Launching Activity) in on create
这是在创建的活动 A(启动活动)中
Bundle extras = getIntent().getExtras();
Title = extras.getString("Title");
Description = extras.getString("Description");
Price = extras.getString("Price");
Availability = extras.getString("Availability");
Then we have me creating the bundle in Activity B
然后我们让我在活动 B 中创建包
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);
回答by Simon
I would suggest the following:
我建议如下:
A. Use Bundle from Intent:
A. 使用来自 Intent 的 Bundle:
Intent pIntent = new Intent(this, JustaClass.class);
Bundle extras = pIntent.getExtras();
extras.putString(key, value);
B. Create a new Bundle:
B. 创建一个新的 Bundle:
Intent pIntent = new Intent(this, JustaClass.class);
Bundle pBundle = new Bundle();
pBundle.putString(key, value);
mIntent.putExtras(pBundle);
C. Use putExtra() method of the Intent:
C. 使用 Intent 的 putExtra() 方法:
Intent pIntent = new Intent(this, JustaClass.class);
pIntent.putExtra(key, value);
Finally in the launched Activity, you can read them hrough:
最后在启动的 Activity 中,您可以通过以下方式阅读它们:
String value = getIntent().getExtras().getString(key)
I just used Strings as an example for passing, I refer to Bundleand Intent.