long click method to delete item from listview

raman rayat picture raman rayat · Jan 5, 2014 · Viewed 9.4k times · Source

could any one help me that how to perform long click option in list view item's so i able to delete my notes from sq lite database ...i have 2 column in my note app they are id ,title and notetext

my code to create table is ..

mydb1 = Main1Activity.this.openOrCreateDatabase("185", MODE_PRIVATE, null);

mydb1.execSQL("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT,title varchar,notetext varchar);");

long click code

lv.setOnItemLongClickListener(new OnItemLongClickListener(){
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
        data.remove(arg2);
        // adapter.notifyDataSetChanged();
        //adapter.notifyDataSetInvalidated();
        return true;
    }
});

Answer

raman rayat picture raman rayat · Jan 12, 2014

yes i got the answer... it will be helpful for other stack flow user's :D :)

public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
    ArrayAdapter <String> adapter = new ArrayAdapter<String>       
                                 (menu.this,android.R.layout.simple_list_item_1,data);
    Cursor cursor2=mydb1.rawQuery("SELECT * FROM notes;", null);

    data.remove(arg2);

    lv.setAdapter(adapter);

    cursor2.moveToPosition(arg2);
    int id= cursor2.getInt(cursor2.getColumnIndex("id"));

    mydb1.delete("notes", "id=?", new String[] {Integer.toString(id)});

    return true ;
}