writing exception to parcel exception while updating contact name in android? - 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?)

Related

A content provider to replace ContactcsContract

Im trying to make some changes to an app that i've downloaded, the app uses ContactContracts to show the list of contacts stored in the phone,
what im trying to do is using a content provider to show a list of contacts that i've stored in my database
the original app uses this method to load contacts from the phone and store the in "contact" object:
public void loadContactsData(){
if(SmsSchedulerApplication.contactsList.size()==0){
System.currentTimeMillis();
String[] projection = new String[] {Groups._ID};
Uri groupsUri = ContactsContract.Groups.CONTENT_URI;
groupCursor = managedQuery(groupsUri, projection, null, null, null);
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor.moveToFirst()){
do{
if(!(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)).equals("0"))){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + id, null, null);
if(phones.moveToFirst()){
Contact contact = new Contact();
contact.content_uri_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
contact.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contact.number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID}, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID + "=" + contact.content_uri_id, null, null);
if(cur.moveToFirst()){
do{
if(!String.valueOf(cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID))).equals(contact.number) && cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID))!=0){
boolean isValid = false;
if(groupCursor.moveToFirst()){
do{
if(!cur.isClosed() && !groupCursor.isClosed() && cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID)) == groupCursor.getLong(groupCursor.getColumnIndex(Groups._ID))){
isValid = true;
break;
}
}while(groupCursor.moveToNext());
}
if(isValid){
contact.groupRowId.add(cur.getLong(cur.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID)));
}
}
}while(cur.moveToNext());
}
cur.close();
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contact.content_uri_id));
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
try{
contact.image = BitmapFactory.decodeStream(input);
contact.image.getHeight();
} catch (NullPointerException e){
contact.image = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.no_image_thumbnail);
}
SmsSchedulerApplication.contactsList.add(contact);
}
}
}while(cursor.moveToNext());
}
}
}
im not familiar with using content provider so im not sure what should i define in my content provider class
You don't have to use a content provider if you don't want to. Also using a contacts provider example to realize an own user database management is the wrong approach here. The provider was evolved multiple times to support all kind of use cases. I mean, just look at the documentation of it. All this tables and and micromanagement. I doubt that you need all of this.
I suggest you do the following. First create you database scheme. Find out what tables do you need and what columns are required for the application to work. Then put it into an sqlite database and define the queries to store and retrieve the contents. This should be all necessary to make the app work.
Then if everything works and you still have the motivation or requirements, create a content provider by using the existing database as the data store withing the provider and declaring URI's to access and modify the content. Of course you then have to rewrite some portions of the existing code. But if you were using the query, update, delete and insert methods of the database, it should be no problem.
Or you do it the hard way and insert your contacts in the contacts provider by inserting raw contacts. But it you don't have to share your contacts with the system (to crate custom actions on existing contacts for example) or other apps, then just don't do it.

How to update existing contact using content provider

I am trying to edit the contact of my phone using content provider. To load data i have used below code and it works fine.
private ArrayList<String> getRecords()
{
ArrayList<String> records=new ArrayList<String>();
Cursor cursor=getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
if (cursor.moveToFirst())
{
String name="";
String phone="";
String id="";
do{
id=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
name =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = id+" "+name+"\n"+phone;
records.add(name);
}
while(cursor.moveToNext());
}
return records;
}
Now i want to edit actually want to change the name of the selected contact. i am trying below code
Uri uri= ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id);
ContentValues values=new ContentValues();
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "<r XX");
getContentResolver().update(uri, values, null,null);
But it is not updating. What can i do know? Please help. I already check over internet as well as other ans but did not find satisfactory ans.
you dont seem to supply the update paramaters properlly:
the method consist of:
getContentResolver().update(uri, values, where, selectionArgs)
the where should contain:
"ContactsContract.CommonDataKinds.Phone._ID+"=?"
and the selectionArgs should contain the id of the contact to update.

Update singel cell of a row in an SQLite database on Android

I wont to update a single cell of a row in the database. However the row contains of 5 columns so and i would like to not passing all the other values as well as they should remain the same.
I have this code snippet:
Cursor cursor = db.query(STATION_TABLE, null, null, null, null, null, null);
//If the database already include some stations.
if(cursor.moveToFirst())
{
ContentValues stationValues = new ContentValues();
for(StopLocation station: stations)
{
stationValues.clear();
//The database already includes the station
if(cursor.getString(POS_STA_ID).equals(station.getId()))
{
values.put(KEY_STA_DISTANCE, "null");
db.update(STATION_TABLE, stationValues, KEY_STA_ID + "=?", new String[]{station.getId()});
}
The db.update method throws this exception:
java.lang.IllegalArgumentException: Empty values
Any ideas on how to solve this?
If I understand the question correctly and assuming you are always dealing with one row, there are two possible ways to approach this:
First:
Get the values of all fields in the entire row, and declare them as content values before updating:
ContentValues cv = new ContentValues();
cv.put("Field1","123");
cv.put("Field2","True")
Second:
Use execSQL() method:
String strSQL = "UPDATE your_table SET Field1 = foo WHERE POST_STA_ID = "+ station.getId();
myDataBase.execSQL(strSQL);

Sqlite open helper insert else update?

I want to insert data successfully
Here is my code:
public void insertData(String strTableName,
ArrayList<HashMap<String, String>> arrListproductdatabase) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for (int i = 0; i < arrListproductdatabase.size(); i++) {
// cv.put(columnName, arrListOfRecord.get(i).get("name"));
cv.put(columnproductname,
arrListproductdatabase.get(i).get("product"));
cv.put(columnproductprice,
arrListproductdatabase.get(i).get("price"));
cv.put(columnproductquantity,
arrListproductdatabase.get(i).get("quantity"));
cv.put(columnproductid,
arrListproductdatabase.get(i).get("productID"));
cv.put(columnresturantID,
arrListproductdatabase.get(i).get("resturantID"));
db.insert(strTableName, null, cv);
}
I want that when I have to press add button again, that time it should check if the product is already inserted, and in that condition it should update and all.
I don't want to create any duplicate value.
Any help would be appreciated!
you can check for the distinct values in the db. please follow the link to have more details
android check duplicate values before inserting data into database
Set 'Product' field as unique key. So when duplicate value arrives from standard insert, it will simply return -1 and the error message will be swallowed.
You can control the behavior by using insertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm) where you also specify a conflict algorithm that can be of values:
CONFLICT_ABORT
CONFLICT_FAIL
CONFLICT_IGNORE
CONFLICT_REPLACE
CONFLICT_ROLLBACK
Check out the reference for descrption of the conflict resolution types.
There is also an updateWithOnConflict
You can do that like this :
public boolean checkProduct(String product){
// shold open database here
Cursor mCursor =
db.query(true, DATABASE_TABLE, null, "product='" + product+"'", null, null, null, null, null);
if(mCursor != null){
mCursor.close();
// shold close database here
return true;
}
// shold close database first here also
return false;
}
Hope this helped you.

how to update a contact in sql lite database in 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;
}

Categories

Resources