how to update a contact in sql lite database in android? - android

In my application, I come up with a thing where I have to add a contact to the favorite list. I used this code to update the starred column of the contact table but all in vain. As far as I think, I am passing null to content values in my query, but I'm unable to figure out the possible correction.
try{
ContentResolver cr = getContentResolver();
String[] projection={ContactsContract.Contacts.STARRED};
Cursor cur = cr.query(CallLog.Calls.CONTENT_URI,projection, null, null, null);
cur.moveToPosition(Integer.parseInt(idholder)); //idholder holds unique row id
cr.update(ContactsContract.Contacts.CONTENT_URI, null, Contacts.STARRED+"="+1, null);
}
catch(SQLiteException sqle){
sqle.printStackTrace();
}

In ContactsContract.ContactOptionsColumns you have a column called STARRED, which is boolean. So all you have to do is update the selected contact

I know its too late to give the answer. But if anyone finding the answer can use this.
private int updateContact(int val,String lookupKey) {
// val = 0/1
// you can also use _ID instead of lookupKey
try {
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(ContactsContract.Contacts.STARRED, val);
return cr.update(ContactsContract.Contacts.CONTENT_URI, values,
ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY+ " = ?",
new String[] {lookupKey});
} catch (Exception e) {
Log.e("TAG", e.toString());
}
return 0;
}

Related

Android content provider query not retrieving updated information

So I've written a query to extract the WhatsApp contacts of a phone. My initial query goes like this:
Cursor c = con.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
new String[]{"com.whatsapp"},
null
);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext()) {
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
myWhatsappContacts.add(c.getString(contactNameColumn));
}
The purpose of this is to find out how many WhatsApp contacts the phone has at any one time. When I do:
Log.i("WhatsApp contacts found:", Integer.toString(myWhatsappContacts.size());
It should print out how many WhatsApp contacts there were into LogCat. And this works - up to a point.
Let's say for example that the number of WhatsApp contacts I have now is 101. The next phase of this little project is to delete away ALL contacts if there are more than 100 of them. In which case, we go:
if (myWhatsappContacts.size() > 100) {
//Delete all contacts code here
}
I've tested the delete contacts code, it works. I check the contacts directory of the phone via the contacts app, and it says 0. But now when I do the query again (refer to code above), it still shows 101! What's going on?
If it helps, my DeleteContacts method is as follows:
private void deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
} finally {
cur.close();
}
return;
}
What am I doing wrong? Is my DeleteContacts code faulty? Or is the query itself faulty?

Get full conversation with Android query

I would like to get all messages from one contact. I have the contact ID _id, so I've already do something like this :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
try {
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, this.contID + "= _id" , null, null); //contID is the unique ID for one contact in our android.
while (cursor.moveToNext()) {
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body")));
}
cursor.close();
}
catch (Exception e) {
System.out.print("ERROR");
}
I've asked something like
SELECT * FROM content://mms-sms/conversations WHERE _id = contID
As you can see, in my query, I ask system for messages from one contact (user id that I know) But I can just display the last message body. So I think it exists others query to get all messages from one user ?
Any ideas ???
I doubt that _id in this case is the id of the contact you are sending sms/mms to but rather the thread's id. The column you probably want to use for your query clause is RECIPIENT_IDS. For debugging purpose try without the where clause and dump the cursor to analyze the results
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, null , null, null);
DatabaseUtils.dumpCursor(cursor);
Sorry for answer too late, but I've found a solution.
Here is my code :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
boolean isMe;
try {
Cursor cursor = cr.query(Uri.parse("content://sms"), null, this.cont.getThread_ID() + " = thread_id" , null, "date ASC");
while (cursor.moveToNext()) {
//if it's a received message :
if ((cursor.getString(cursor.getColumnIndexOrThrow("person")) != null)) {
isMe = false;
}
else {
//it's a message sent by me.
isMe = true;
}
date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body") + "\n");
}
cursor.close();
}
Thanks to "conent://sms" table, I can get all sms !
So I've used thread_id to display all messages, and thanks to the person column, I can know if the message was sent by me or my contact.

How to check the value already excists or not in sqlite db in android?

In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE

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
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?)

aggregated contacts are created automatically exception while executing insert statement in contact table?

I used insert statement with callog.calls table and it worked fine but in contact table when I am trying to update starred column I get this unsupported exception:aggregated contacts are created automatically.I have no clue what this mean and how to get rid of this.kindly help.thanks in advance.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
ContentValues value=new ContentValues();
value.put(ContactsContract.Contacts.STARRED,true);
cur.moveToFirst();
while(!cur.isLast()){
if(some condition)
{
try{
cr.insert(ContactsContract.Contacts.CONTENT_URI, value) ;
}
catch(Exception e)
{
e.printStackTrace();
}
} //if
cur.moveToNext();
} //while

Categories

Resources