如何从sqlite中删除listview中的数据?

时间:2014-03-25 13:01:33

标签: android sqlite listview

我在上下文菜单中创建了一个删除选项。删除功能正常,但存在问题。无论我选择删除列表视图中的哪个项目,它都只会删除最后一项。如何删除要删除的项目?

public class Watchlist extends ListActivity {

private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHandler.TABLE_ITEM;
private SQLiteDatabase newDB;

String pid, iid, name, price, date, type;
private ArrayAdapter<String> adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    openAndQueryDatabase();
    setContentView(R.layout.activity_watchlist);
    displayResultList();
}

private void displayResultList() {
    TextView tView = new TextView(this);
    tView.setText("This data is retrieved from sqlite");
    ListView lv = getListView();
    lv.addHeaderView(tView);
    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, results);
    lv.setTextFilterEnabled(true);
    lv.setAdapter(adapter);
    registerForContextMenu(lv);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, v.getId(), 0, "Delete");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
            .getMenuInfo();
    // info.position will give the index of selected item
    int menuItemIndex = info.position;

    String menuItemIndexS = String.valueOf (menuItemIndex);
    Log.d ("value",menuItemIndexS);
    if (item.getTitle() == "Delete") {
        DatabaseHandler db = new DatabaseHandler(Watchlist.this);
        Log.d("Delete: ", "Deleting .."); 
        int pidI = Integer.parseInt(iid);

        db.deleteItem(new Items(pidI, name, price, date, type));
        Intent i = new Intent(this, Watchlist.class);
        startActivity(i);
        finish();
    }
    return true;
}

private void openAndQueryDatabase() {
    try {
        DatabaseHandler db = new DatabaseHandler(Watchlist.this);
        newDB = db.getWritableDatabase();
        Cursor c = newDB.rawQuery("SELECT * FROM " + tableName, null);

        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    pid = c.getString(c.getColumnIndex("id"));
                    iid = c.getString(c.getColumnIndex("iid"));
                    name = c.getString(c.getColumnIndex("name"));
                    price = c.getString(c.getColumnIndex("price"));
                    date = c.getString(c.getColumnIndex("created_at"));
                    String type = c.getString(c.getColumnIndex("type"));
                    results.add("Name: " + name + "\nPrice: " + price
                            + "\nDate posted: " + date + "\nItem type: "
                            + type);
                } while (c.moveToNext());
            }
        }
    } catch (SQLiteException se) {
        Log.e(getClass().getSimpleName(),
                "Could not create or Open the database");
    } finally {
        if (newDB == null)
            newDB.execSQL("DELETE FROM " + tableName);
        newDB.close();
    }

}
}

3 个答案:

答案 0 :(得分:0)

你正在使用iid String var。这是从数据库中检索并存储最后一个iid值,因为您从表中获取所有值。所以根据我的理解:-)  你的代码。将iid更改为info.position。

 if (c.moveToFirst()) {
                do {
                    pid = c.getString(c.getColumnIndex("id"));
 **/*that's why it's deleting last item :-) **/
                    iid = c.getString(c.getColumnIndex("iid"));**
                    name = c.getString(c.getColumnIndex("name"));
                    price = c.getString(c.getColumnIndex("price"));
                    date = c.getString(c.getColumnIndex("created_at"));
                    String type = c.getString(c.getColumnIndex("type"));
                    results.add("Name: " + name + "\nPrice: " + price
                            + "\nDate posted: " + date + "\nItem type: "
                            + type);
                } while (c.moveToNext());
            }

答案 1 :(得分:0)

iid是一个全局变量。您正在do ... while方法中的openAndQueryDatabase循环内更改它的值。这就是为什么onContextItemSelected iid的值将是数据库查询的最后一个值。

解决问题的一种快速方法是使用另一个ArrayList在循环中存储resultsIds

results.add("Name: " + name + "\nPrice: " + price
                            + "\nDate posted: " + date + "\nItem type: "
                            + type);
resultsId.add(iid);

然后在onContextItemSelected

db.deleteItem(new Items(resultsId.get(menuItemIndex ), name, price, date, type));

答案 2 :(得分:0)

adapter.remove(adapter.getItem(info.position));