关于如何从列表中删除项目有很多问题,但我找不到我要找的那个。
基本上,我有一个列表和数据库,如何从列表和数据库中删除?
因为我的列表从ArrayList<String>
填充,所以一个项目只是字符串。例如,我的列表中有两个项目,如1.John,Doe 2.Jane,Doe
我如何获得这些物品ID?
如果我使用此代码并通过单击项目来检查ID:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
Long.toString(parent.getItemIdAtPosition(position)) ,
Toast.LENGTH_SHORT).show(); }});
它显示0或1但不是1或2.(这是非常合乎逻辑的)
那么,我怎么得到那些物品ID?我现在能想到的唯一选择是获取我的列表项的前两个或三个字符并将它们转换为int并传递给我的SQL语句,然后从DB中删除相应的项目。
也许有人有更好的想法?
编辑:
private void getAllData()
{
cursor = myDataBase.rawQuery("SELECT * FROM " +
MY_TABLE, null);
if (cursor != null)
{
if (cursor.moveToFirst())
{
do
{
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String persName = cursor.getString(cursor.getColumnIndex("Name"));
String persSurname= cursor.getString(cursor.getColumnIndex("Surname"));
results.add("" + id + ", " + persName + ", " + persSurname);
} while (cursor.moveToNext());
}
cursor.close();
}
}
而results
是private List<String> results = new ArrayList<String>();
我希望这就是你所要求的。
答案 0 :(得分:1)
您应该从SimpleCursorAdapter类而不是您当前正在进行的操作扩展到仅传递String
个对象。这个example应该让您开始将数据放入适配器。
但是,如果您只想修改当前正在进行的操作,我建议如下。除了ArrayList<String> results
之外,我还会创建一个额外的对象ArrayList<Integer> resultsIds
来保存每个项目的ID。
results.add("" + id + ", " + persName + ", " + persSurname);
resultsIds.add(id);
然后在您的点击监听器中执行以下操作:
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
int id = resultsIds.get(position); // this is the id for the item in the database you want to delete
// now with your myDataBase SqliteDatabse object delete the item from the databse.
// then remove it from the list
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
adapter.remove( results.get(position) );
// and you'll probably now want to remove the String and id from your results
results.remove(position);
resultsIds.remove(position);
}
答案 1 :(得分:0)
使用onListItemClick和参数id代替:
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
//TODO:
}