我一整天都在寻找答案,所以希望有人可以帮助我。
我有一段代码应该从从SQLite DB创建的ListView中选择一个项目,将其返回到字符串,这样我就可以运行SQL命令从DB中删除记录。但是,当单击该条目时,它将从其下方的条目而不是所选的条目返回数据,因此我认为它选择了错误的索引。
如果有3个条目,比如Adam,Bob和Charlie,如果我点击Adam,它会将Bob返回给字符串;如果我点击鲍勃,它将返回查理;如果我点击查理,它将抛出一个IndexOutOfBoundsException!
我的代码如下:
public class viewdb extends ListActivity {
private static final int DELETE_ID = Menu.FIRST + 1;
private static final int EDIT_ID = Menu.FIRST + 2;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBAdapter.DATABASE_TABLE;
private SQLiteDatabase newDB;
String strfieldName;
String strSelFN;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CalledActivity", "OnCreate");
Intent in = new Intent();
openAndQueryDatabase();
displayResultList();
registerForContextMenu(getListView());
}
public void displayResultList() {
TextView tView = new TextView(this);
tView.setText("Fields in Database");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
public void openAndQueryDatabase() {
try {
DatabaseHelper dbHelper = new DatabaseHelper(
this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT Field_Name FROM " + tableName,
null);
if (c != null) {
if (c.moveToFirst()) {
do {
strfieldName = c.getString(c.getColumnIndex("Field_Name"));
results.add(strfieldName);
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or open the database");
newDB.close();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
strSelFN = o.toString();
getListView().showContextMenu();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Entry Menu");
menu.add(Menu.NONE, EDIT_ID, Menu.NONE, R.string.strEdit);
menu.add(Menu.NONE, DELETE_ID, Menu.NONE, R.string.strDelete);}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == DELETE_ID) {
// newDB.execSQL("DELETE FROM " + tableName +
// " WHERE Field_Name = '" + strSelFN + "'");
Toast.makeText(this, "Field Deleted: " + strSelFN,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
我还没有定义EDIT_ID,因为DELETE_ID函数需要主要工作。
由于
答案 0 :(得分:0)
而不是
Object o = this.getListAdapter().getItem(position);
使用
Object o = this.getListView().getItemAtPosition(position);
getListAdapter
返回的ListAdapter不知道您的标题视图,因此索引关闭了1。