Deleting item from ListView deletes some another item from SQLite database

删除回忆录丶 提交于 2019-12-02 13:11:52

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));
}
});

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.

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