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!
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".
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
. 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());
精彩评论