Search code examples
androidsqlitecalllog

writing exception to parcel exception while updating contact name in android?


I need to update a column (cached_name) of table callog.calls in sql lite database in android.what I can't figure out is how to use update statement.I am unable to find anything regarding update command using cursor.kindly help.thanks in advance.

 //number1 is the phone number against which I need to run update query in db.
 //name is the string which I used to insert against number1..              

      String name=edittext.gettext().tostring();           
        ContentResolver cr = getContentResolver(); 
        Cursor cur = cr.query(CallLog.Calls.CONTENT_URI,
                    null, null, null, null);
        ContentValues value=new ContentValues();

        value.put("CallLog.Calls.CACHED_NAME",name);

        cur.moveToFirst();  
        while(!cur.isLast())
        {                   
              String number=cur.getString(cur.getColumnIndex(CallLog.Calls.NUMBER));                    
              if((number.equals(number1)==true)
              {  
                    try{                   
                         cr.update(CallLog.Calls.CONTENT_URI,value,CallLog.Calls.CACHED_NAME+"=?",null);
                    }
                    catch(Exception e)
                    {
                         e.printStackTrace();
                         System.out.println(e.getStackTrace()); 
                    }
             }//if  
             cur.moveToNext();   
        }//while

Solution

  • Basically, the only line you actually need is the update :

    String name = edittext.getText().toString();
    ContentResolver cr = getContentResolver(); 
    
    ContentValues value = new ContentValues();
    // Note that there is no "" here. The value is a constant
    value.put(CallLog.Calls.CACHED_NAME, name);
    
    cr.update(CallLog.Calls.CONTENT_URI, values, CallLog.Calls.NUMBER+"=?",
        new String[] { number1 });
    

    This is equivalent to this raw SQL query:

    UPDATE call_log SET cached_name = name WHERE number = number1;
    

    There is no need for iterating over all the calls, that's what the where clause is for.

    Also,

    while(!cur.isLast())
    

    prevents you from actually reading the last matching value. Don't do that. Use

    while (cur.moveToNext())
    

    when you need to iterate over a cursor (which you don't, here)

    I strongly suggest you take a look at how cursors work, as well as how sql works.

    (Also, out of curiosity, why do you need to modify the callLog table?)