intent.putExtra 不起作用

5

我需要在两个活动之间传递信息,但由于某些原因,信息没有被发送/接收。

LogCat没有给出任何错误。调试器清楚地显示意图(变量:mExtras)添加了一些东西,但很难解释到底添加了什么内容。此后它给出“源代码未找到”的提示,并没有提供更多帮助。

但首先,我们需要确定是否已经完成正确的操作:

发送:

Intent intent = new Intent ( this, TaskListActivity.class );
intent.putExtra ( ProjectManager.ID, mId.toString () );
startActivity ( intent );

接收:

Intent intent = getIntent ();
mId = UUID.fromString ( intent.getStringExtra ( ProjectManager.ID ) );

你试过那些答案了吗?它们有效吗? - Subramanian Ramsundaram
还没有成功。还在努力中。:/ - abc32112
你找到问题了吗? - Dent7777
5个回答

1
在“intent”后添加以下代码:
Bundle extras = intent.getExtras();
String exampleString = extras.getString(ProjectManager.ID);

1

什么是ProjectManager.ID?在从putExtra接收数据时,您应该传递相同的唯一key,即使接收数据的方式错误,也要检查下面的代码:

发送:

Intent intent = new Intent ( this, TaskListActivity.class );
intent.putExtra (ProjectManager.ID, mId.toString () );
startActivity ( intent );

收到:
Bundle extras = intent.getExtras();
    if(extras!=null){
  String _Str = extras.getString(ProjectManager.ID);
}

它是在另一个类中定义的常量(字符串)。 - abc32112
ProjectManager.ID在两个活动中包含相似的数据吗? - RobinHood
是的。ID指的是同一个字符串。 :) - abc32112
在将数据发送到另一个活动之前,请检查/打印日志“mId.toString()”,它确实包含值吗? - RobinHood
这个 bundle 真的很令人困惑,但是我可以在调试器中找到键和值,它们在发送之前会被多次找到,原因不明。所以,看起来它们没有被接收到。 - abc32112

0

在新的活动中检索额外信息:

String valueOfExtra;
Intent i = getIntent();
//check first
if(i.hasExtra("extra1")){
  valueOfExtra = i.getStringExtra("extra1");
}

0

尝试这个以获得额外的奖励:

Bundle extras = getIntent().getExtras(); 
String id;

if (extras != null) {
    id= extras.getString(key);

}

我不知道你具体在哪里遇到了困难。请参考这篇文章:http://www.vogella.com/articles/AndroidIntent/article.html - Subramanian Ramsundaram
我也是。看起来很简单,但就是不起作用。奇怪。 - abc32112

0
在 FirstActivity.java 中编写以下代码。
 Intent i = new Intent(FirstActivity.this,SecondActivity.class);
 i.putExtra("KEY",value);
 startActivity(i);

在SecondActivity.java中:
Bundle extras=getIntent().getExtras();
String name=extras.getString("key"); //if data you are sending is String.
int i=extras.getInt("key"); //if data you are sending is integer.

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