[英]Why does my Android activity force close when I try to access info I put in the bundle?
I am writing an Android app. 我正在编写一个Android应用程序。 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.
活动之一是ListActivity,因此当人员在列表中选择一个项目时,我希望将该项目的文本值存储在Intent / Bundle中,以便下一个活动知道该值。 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: 要启动的活动的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");
}
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. 当我从ListActivity的列表中单击一个项目时,它开始执行onCreate代码,但是当它到达尝试检索字符串值的行时,将显示一个强制关闭对话框。
I don't have much experience passing information with a Bundle, so I would appreciate any and all help! 我在使用Bundle传递信息方面经验不足,因此,我将不胜感激!
nameB = savedInstanceState.getString("com.example.myapp.Name");
should be replaced with 应该替换为
Bundle bundle = getIntent().getExtras();
nameB = bundle.getString("com.example.myapp.Name");
try that out and see if it helps. 试试看,看看是否有帮助。
Use adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine your stack trace and see the exception that triggered your "force close". 在Eclipse中使用
adb logcat
,DDMS或DDMS透视图检查您的堆栈跟踪,并查看触发“强制关闭”的异常。
In this case, I suspect that you will find that what you put into the Bundle
is not a String
, since getText()
does not return a String
. 在这种情况下,我怀疑您会发现放入
Bundle
内容不是String
,因为getText()
不会返回String
。 However, that is just a guess -- your stack trace should tell you more. 但是,这只是一个猜测-您的堆栈跟踪应该告诉您更多信息。
Among other problems 除其他问题外
intent.putExtra("com.example.myapp.Name", ((TextView) view).getText());
Should be 应该
intent.putExtra("com.example.myapp.Name", ((TextView) view).getText().toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.