当我尝试访问我放入捆绑包中的信息时,为什么我的 Android 活动会强制关闭?
我正在编写一个 Android 应用程序。其中一个活动是 ListActivity,因此当用户选择列表中的某个项目时,我希望将该项目的文本值存储在 Intent/Bundle 中,以便下一个活动知道该值。我的代码如下所示:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent intent = new Intent(view.getContext(), FavoriteEditFromDest.class);
intent.putExtra("com.example.myapp.Name", ((TextView) view).getText());
startActivity(intent);
}
});
}
要启动的活动的 onCreate 方法如下所示:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite_dest_edit);
// nameB is a global string variable defined above.
nameB = savedInstanceState.getString("com.example.myapp.Name");
}
当我单击 ListActivity 中列表中的某个项目时,它开始执行 onCreate 代码,但是当它到达以下行时尝试检索字符串值时出现强制关闭对话框。
我没有太多使用捆绑包传递信息的经验,所以我将不胜感激任何和所有的帮助!
I am writing an Android app. One of the activities is a ListActivity, so when the person selects an item in the list I would like the text value of that item to be stored in the Intent/Bundle so that the next activity knows that value. My code looks something like this:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Intent intent = new Intent(view.getContext(), FavoriteEditFromDest.class);
intent.putExtra("com.example.myapp.Name", ((TextView) view).getText());
startActivity(intent);
}
});
}
The onCreate method for the activity that is to be started looks like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite_dest_edit);
// nameB is a global string variable defined above.
nameB = savedInstanceState.getString("com.example.myapp.Name");
}
When I click an item from the list in the ListActivity, it begins to execute the onCreate code, but when it gets to the line that tries to retrieve the string value I get a force close dialog.
I don't have much experience passing information with a Bundle, so I would appreciate any and all help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该替换为
尝试一下,看看是否有帮助。
should be replaced with
try that out and see if it helps.
使用
adb logcat
、DDMS 或 Eclipse 中的 DDMS 透视图检查堆栈跟踪并查看触发“强制关闭”的异常。在这种情况下,我怀疑您会发现放入
Bundle
中的内容不是String
,因为getText()
不会返回一个字符串
。然而,这只是一个猜测——你的堆栈跟踪应该告诉你更多信息。Use
adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine your stack trace and see the exception that triggered your "force close".In this case, I suspect that you will find that what you put into the
Bundle
is not aString
, sincegetText()
does not return aString
. However, that is just a guess -- your stack trace should tell you more.除其他问题外,
应该是
Among other problems
Should be