Question

I have a list view where my SQL query will be displayed. Now I have added an OnItemClickListener to delete entrys on click:

lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View arg1,int arg2, long arg3){
    ListView lv = (ListView) findViewById(R.id.listView1);      
    final String Name = lv.getAdapter().getItem(arg2).toString();
    final String ID = String.valueOf(arg3);

    CharSequence dbeintrag = getString(R.string.dbeintrag);
    CharSequence yes = getString(R.string.yes);
    CharSequence no = getString(R.string.no);
    Builder alertDialog = new AlertDialog.Builder(EP.this);
    alertDialog.setTitle(Name);
    alertDialog.setMessage(dbeintrag);
    alertDialog.setCancelable(true);
    alertDialog.setPositiveButton(yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            deleteentry(Name,ID);
            fillSQLData(); // refresh
        } }); 

    alertDialog.setNegativeButton(no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        } }); 
    alertDialog.show();
}
});  

}

 public void deleteentry(String Name,long ID) // Lösche Eintrag
    {
        DataBaseHelper myDbHelper = new DataBaseHelper(null);
        myDbHelper = new DataBaseHelper(this);

        ID = ID+1; // Anpassen zur DB

        SQLiteDatabase database = myDbHelper.getWritableDatabase();
        database.execSQL("DELETE FROM Heute WHERE Name='"+Name+"' and _id='"+ID+"'");
        mPLAdapter.notifyDataSetChanged();
    }

Now I have the problem that my ID in the Database is not the ID I get from the onItemClick function. For example, I'll add 3 entries, delete all, add 3 new ones. For the function the first entry is 0, in the SQL database its 4...

What is the best solution to fix this?

Than you very much!

Was it helpful?

Solution

Override this method to your adapter class so you can retrieve the id in onItemClick.

@Override
public long getItemId(int position) {
    return yourList.get(position);
}

In onItemClick

final String ID = String.valueOf(lv.getAdapter().getItemId(arg2)); 
//long id = ((YourAdapter)parent.getAdapter()).getItemId(arg2);

Please see Android OnItemClickListener long id parameter is not giving field id and view.getId() returning wrong id in OnItemClickListener

Edit: so here's Oli's changes:

final long id = ((EPListAdapter)arg0.getAdapter()).getItemId(arg2);

"Its important to use .notifyDataSetChanged(); on the Adapter. Else it wont work."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top