mardi 20 janvier 2015

Deleting the row in database is not working.How to get the ID of the row i clicked?

Each row have a id and phone number. I know the position and id are differing. but i got the id of the position through getitemID. and still not working.

How to get the ID of the row i clicked?



public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
mainListView = (ListView) findViewById( R.id.mainListView );
// DatabaseHandler db = new DatabaseHandler(this);

/**
* CRUD Operations
* */


ArrayList<String> planetList = new ArrayList<String>();

// Reading all contacts

contacts = db.getAllContacts();

for (Contact cn : contacts) {
log = "ID"+cn.getID()+"Phone: " + cn.getPhoneNumber();


// Writing Contacts to log
planetList.addAll( Arrays.asList(log) );
}

listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
mainListView.setAdapter( listAdapter );
registerForContextMenu(mainListView);
}

public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
try
{

// info.position will give the index of selected item

if(item.getTitle()=="DELETE")
{
Contact cn= new Contact();

//cn._id=info.position+1;

cn._id= Math.abs((int)listAdapter.getItemId(info.position));
db.deleteContact(new Contact(cn._id,cn._phone_number));
listAdapter.remove(listAdapter.getItem(info.position));

listAdapter.notifyDataSetChanged();

}
else
{
return false;
}

return true;
}
catch(Exception e)
{
return true;
}
}

}


DELETE CODE



void deleteContact(Contact contact) {

SQLiteDatabase db = this.getWritableDatabase();

String DELETE_ID= "DELETE FROM " + TABLE_CONTACTS +" WHERE"+""+KEY_ID+"="+contact._id;

db.execSQL(DELETE_ID);

}

Aucun commentaire:

Enregistrer un commentaire