1

I'm creating an android app that requires database connectivity, for which I'm using the inbuilt SQLiteDatabase class. My database has been created using the following statement:-

SQLiteDatabase db;
db = openOrCreateDatabase("ContactsMain",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.execSQL("Create Table Contacts (name Text, phno Text PRIMARY KEY, important Integer)");

'important' has values of either 0 or 1, based on whether the contact is important. To update this value, I'm using the following code:

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    c.moveToPosition(position);
    String ph = c.getString(c.getColumnIndex("phno"));
    ContentValues val = new ContentValues();
    val.put("important",1);
    String query = "update Contacts set important = 1 where phno=" + ph + ";";
    db.update("Contacts", val, query, null);
    c.close();
    db.close();
}       

db and c have been initialized as follows:

SQLiteDatabase db = openOrCreateDatabase("ContactsMain",SQLiteDatabase.CREATE_IF_NECESSARY,null);
Cursor c = db.rawQuery("SELECT * FROM Contacts",null);    

Problem is, when I click on an item in the list, the value of 'important' is set to 1 for all contacts, not just the one selected. Could someone help me out here?

2
  • Justgive important value as dynamically Commented Nov 14, 2012 at 5:40
  • @ADR : Could you elaborate? I don't understand. Commented Nov 14, 2012 at 5:51

2 Answers 2

1

This will work for you

protected void onListItemClick(ListView l, View v, int position, long id) {
   super.onListItemClick(l, v, position, id);


  c.moveToPosition(position);
  String ph = c.getString(c.getColumnIndex("phno"));

  String where = "phno=?";
  String[] whereArgs = new String[] {ph};    

  ContentValues val = new ContentValues();
  val.put("important",1);

  db.update(DATABASE_TABLE, val, where, whereArgs);
  c.close();
  db.close();

}       
Sign up to request clarification or add additional context in comments.

3 Comments

This will update all the records in the database, not just one.
This looks good to me, except that I do not think you should be closing the cursor here.
All the records are being updated, and that is the problem! I want only the item selected from the list to be updated. How do I do that? I tried the approach given in the first answer, still didn't work.
0

You want

ContentValues val = new ContentValues();
val.put("important", 1);
db.update("Contacts", val, "phno=?", new String[] {ph});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.