在我的应用程序中,我得到一个强制关闭,我不知道如何解决这个问题。问题是我有一个扩展ListActivity的类。在这个课程中有一个商店列表,用户应该选择其中一个商店。如果他没有选择商店并按下按钮返回我得到强制关闭,因为上一课期望商店的名称。我怎样才能发现这个错误?
以下是我选择商店的课程:
public class SelectShop extends ListActivity {
private ListView lv1;
SimpleCursorAdapter adapter = null;
Cursor cursor;
DbAdapter db;
ImageView iconshop;
private static final int ADD=Menu.FIRST;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopselect);
iconshop = (ImageView) findViewById(R.id.iconshop);
lv1 = getListView();
DbApplication myApplication = (DbApplication) this.getApplication();
db= myApplication.getDatabaseAdapter();
cursor = db.getAllShops();
startManagingCursor(cursor);
if (cursor != null && cursor.moveToFirst()){
adapter = new SimpleCursorAdapter(this, R.layout.shopsrow, cursor,
new String[] { DbAdapter.NAME, DbAdapter.ADRESS }, new int[] {
R.id.title, R.id.address });
setListAdapter(adapter);
}else Toast.makeText(this,
"Choose Menu for adding a shop",
Toast.LENGTH_LONG).show();
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent j = new Intent(SelectShop.this,
com.ShoppingList.NewList.class);
Cursor c = (Cursor) parent.getAdapter().getItem(position);
j.putExtra("shop", c.getString(c.getColumnIndex(db.NAME)));
setResult(RESULT_OK, j);
finish();
}
});
}
/*Adaugarea meniului Add Shop*/
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, ADD, 0, "Add Shop").setIcon(R.drawable.additem);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ADD:
Intent j = new Intent(SelectShop.this, Shops.class);
startActivityForResult(j, 0);
return true;
}
return false;
}
}
在previuos课程中我有这个:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case 0: {
Bundle b = intent.getExtras();
shopselect = b.getString("shop");
shop.setText(shopselect);
}
break;
}
}
答案 0 :(得分:1)
你必须检查onActivityResult中的空状态,如下所示。
if(b != null)
{
shopselect = b.getString("shop"); shop.setText(shopselect);
}
答案 1 :(得分:0)
检查结果代码。只有在结果代码是Activity.RESULT_OK时才能做你的事。
答案 2 :(得分:0)
我认为您需要实施一种机制,在不选择列表中的任何项目的情况下,不会让您的用户返回到之前的活动。覆盖您的onKeyDown()
方法,当用户按下返回键时,您应检查是否选择了任何项目。如果不是,您可以抛出一个警告对话框,告知用户他必须做什么才能继续。希望这有帮助!