Deleting item from ListView deletes some another item from SQLite database

别等时光非礼了梦想. 提交于 2020-01-11 14:28:08

问题


If I delete an item from listView suppose item_no = 5, then some another item gets deleted from database whose id is not 5.

Here is my code.

My database class TRDBHelper.class

//Get single reminder
Cursor getReminder(int id){

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_ID, COLUMN_TITLE, COLUMN_DES,
                            COLUMN_DATE, COLUMN_TIME}, COLUMN_ID + "=?",
                            new String[]{String.valueOf(id)}, null, null, null, null);
    if(cursor != null)
        cursor.moveToFirst();

    return cursor;
}

//Get all reminders
public  List<TRListFormat> getAllReminders(){

    List<TRListFormat> remList = new ArrayList<>();

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);

    if(cursor.moveToFirst()){
        do {
            TRListFormat format = new TRListFormat();
            format.setId(Integer.parseInt(cursor.getString(0)));
            format.setTitle(cursor.getString(1));
            format.setDes(cursor.getString(2));
            format.setDate(cursor.getString(3));
            format.setTime(cursor.getString(4));

            remList.add(format);
        } while(cursor.moveToNext());
    }
    return remList;
}

//Delete single reminder
public void deleteReminder(int id){

    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{ String.valueOf(id)});
    db.close();
}

My list view TRList.class

I have use SimpleAdapter in listView and TRListForamat class has all getter and setter methods. Delete button is set on AlertDialog which pops when listView item is clicked

ListView lv;
SimpleAdapter adapter;
ArrayList<HashMap<String, String>> items;
List<TRListFormat> list;
TRDBHelper trDb;

public void refreshList() {
    items = new ArrayList<>();
    list = trDb.getAllReminders();

    for (TRListFormat val : list) {
        HashMap<String, String> map = new HashMap<>();
        map.put("title", val.getTitle());
        map.put("description", val.getDes());
        map.put("date", val.getDate());
        map.put("time", val.getTime());

        items.add(map);
    }
    adapter = new SimpleAdapter(this, items, R.layout.tr_list_format,
            new String[]{"title", "description", "date", "time"},
            new int[]{R.id.tbr_title, R.id.tbr_des, R.id.tbr_date, R.id.tbr_time});

    lv = (ListView) findViewById(R.id.tbr_list);
    lv.setAdapter(adapter);
}

new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {

    int remId = (int)id + 1;  //id is a value from public void onItemClick(final AdapterView<?> adapterView, View view, final int position, final long id)  
                              //I also tried using position instead of id but both gives same result
    adapter.getItem(remId);
    adapter.getClass();

    Cursor rs = trDb.getReminder(remId);
    String id = rs.getString(rs.getColumnIndex(TRDBHelper.COLUMN_ID));
    String title = rs.getString(rs.getColumnIndex(TRDBHelper.COLUMN_TITLE));

    trDb.deleteReminder(Integer.parseInt(id));

    Toast.makeText(getApplicationContext(), "id: "+id+" title:"+title+" deleted", Toast.LENGTH_SHORT).show();

    refreshList();
}

What change do I need to delete same item from listview and database as well?

Can it be done with SimpleAdapter or I need to use SimpleCursorAdapter?


回答1:


You can add and id in the item as hidden textview.

    map.put("id", val.getId());

and in the SimpleAdapter.

Later you can use this to get clicked item

mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
{
    HashMap<String, Object> obj = (HashMap<String, Object>) adapter.getItem(position);
    String id = (String) obj.get("id");

    //delete remider by id
    trDb.deleteReminder(Integer.parseInt(id));
}
});



回答2:


In your TRDBHelper.class add this method:

public int getItemIdByPosition(int position) {
     cursor.moveToPosition(position);
     return Integer.parseInt(cursor.getString(0));
}

call this method in your listView's onItemClickListener with the position, and you will have good id.




回答3:


When using SimpleAdapter row id is the same as position: SimpleAdapter.java#106. In your case: remId is always position + 1.

To have more control I recommend extending BaseAdapter:

public class MyAdapter extends BaseAdapter {
    private Context mContext;
    private List<TRListFormat> mList;

    public MyAdapter(Context context, List<TRListFormat> list) {
        mContext = context;
        mList = list;
    }

    @Override
    public int getCount() {
        if (mList != null) {
            return mList.size();
        } else {
            return 0;
        }
    }

    @Override
    public TRListFormat getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return getItem(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //todo create your view
        return null;
    }
}

Now OnItemClickListener will return correct id value.

EDIT:

If you don't want to use BaseAdapter you can override SimpleAdapter getItemId method.

First add id to map:

for (TRListFormat val : list) {
    HashMap<String, String> map = new HashMap<>();
    map.put("id", val.getId());
    ....
}

Next override getItemId (not best solution but it should work):

SimpleAdapter simpleAdapter = new SimpleAdapter(...) {
    @Override
    public long getItemId(int position) {
        return Long.valueOf(((Map<String,String>) getItem(position)).get("id"));
    }
};


来源:https://stackoverflow.com/questions/28393156/deleting-item-from-listview-deletes-some-another-item-from-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!