How to Add Contacts to Contacts Table - android

I am trying to insert a contact through my application but i am not able to figure out what should be the value of accountType and accountName as below.
ContentValues values = new ContentValues();
values.put(RawContacts.ACCOUNT_TYPE, accountType);
values.put(RawContacts.ACCOUNT_NAME, accountName);
Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME, "Mike Sullivan");
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,"1-800-111-411");
getContentResolver().insert(Data.CONTENT_URI, values);
Also when i try to execute this code with the following changes in the accountType and accountName, i am unable to see it in the Contacts.
values.put(RawContacts.ACCOUNT_TYPE, "acc_type");
values.put(RawContacts.ACCOUNT_NAME, "acc_name");
But it seems that some values get inserted as when i search for "Mike Sullivan" i get the contact but without the Phone Number.
Please Help

below is the code to add contact database and also it return whether the contact was added or not::::
//to save contact in Database
public boolean SaveContact(Activity _activity,String name,String number) {
String MIMETYPE_RADUTOKEN = "vnd.android.cursor.item/radutoken";
String szname = name,szMobile = number;
//Create a new contact entry!
String szToken = String.format("RADU_TOKEN_%d", System.currentTimeMillis());
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(RawContacts.ACCOUNTTYPE, null).withValue(RawContacts.ACCOUNT_NAME, null).build());
//INSERT NAME
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactInsertIndex).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, szname).build());
//INSERT PINLESSMAX MOBILE NUMBER
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, szMobile).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM).withValue(ContactsContract.Data.DATA3, "PinLessMax").build());
// SAVE CONTACT IN BCR Structure
Uri newContactUri = null;
//PUSH EVERYTHING TO CONTACTS
try{
ContentProviderResult[] res = _activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY,ops);
if (res!=null && res[0]!=null) {
newContactUri = res[0].uri;
}
}catch (RemoteException e) {
// error
newContactUri = null;
} catch (OperationApplicationException e) {
// error
newContactUri = null;
}
if (newContactUri == null) {
return false;
}
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szname);
ContentResolver cr = _activity.getContentResolver();
Cursor idCursor = _activity.getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
String tokenWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] tokenWhereParams = new String[]{szId, MIMETYPE_RADUTOKEN};
Cursor tokenCur = cr.query(ContactsContract.Data.CONTENT_URI, null, tokenWhere, tokenWhereParams, null);
while (tokenCur.moveToNext()) {
String token = tokenCur.getString(tokenCur.getColumnIndex(ContactsContract.Data.DATA1));
// CHECK THE TOKEN!
if (szToken.compareTo(token) == 0) {
tokenCur.close();
foundToken = true;
break;
}
}
tokenCur.close();
if (foundToken) break;
}
idCursor.close();
return true;
}//SaveContact()

You can give null values for account type and account name if you do not want to create the contact under a specific account
values.put(RawContacts.ACCOUNT_TYPE, null);
values.put(RawContacts.ACCOUNT_NAME, null);
In most of the devices it creates as a default phone contact.
If you want to know all the account types available in the device,
You can use the following code
Account[] accountList = AccountManager.get(this).getAccounts();
for(int i = 0 ; i < accountList.length ; i++) {
System.out.println(accountList[i].type);
}
Note: Different OEMs uses different name for account type.

Related

Method to return contacts phone number always returns null - Android [duplicate]

I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).
In my onCreate I have this code
String phoneNum = getPhoneNumber(myID);
TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
phoneTextView.setText(phoneNum);
This is the method for getPhoneNumber()
protected String getPhoneNumber(String id) {
ArrayList<String> phones = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cursor.moveToNext()) {
phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursor.close();
String phoneNum;
phoneNum = phones.get(0);
return phoneNum;
}//end getPhoneNumber();
}
This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() != 0) {
int numContacts = cursor.getCount();
ArrayList<String> idList = new ArrayList<>();
Random rand = new Random();
int randomNum = rand.nextInt(numContacts);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
idList.add(id);
}
myID = idList.get(randomNum);
String myString = Integer.toString(randomNum);
TextView myTextView = (TextView) findViewById(R.id.textViewID);
myTextView.setText(myString);
if (myID != null) {
myTextView.setText(myID);
} else {
myTextView.setText("Try Again!");
}
} else {
Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
}
cursor.close();
// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
//signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.Data.MIMETYPE + "=?",
new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
private String getEmail(String id) {
String email = "";
ContentResolver cr = getContentResolver();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
return email;
}
I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work
I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:
private String retrieveContactNumber(String contactName) {
Log.d(TAG, "Contact Name: " + contactName);
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactName},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}

How to get contact id after add a new contact in android?

I use following code for new contacts added to phone.
private static void addContact(Account account, String name, String username,String phone,String email) {
Log.i(TAG, "Adding contact: " + name);
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
builder.withValue(RawContacts.SYNC1, username);
operationList.add(builder.build());
//NAME adding area
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
operationList.add(builder.build());
// Phone Number adding area
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
operationList.add(builder.build());
}
This code work fine for adding a new contact.
I want to update my contacts from server to phone. So I need contact id for updating purpose.
Can I get contact id from above code?. If anybody known share your answer.
If any questions or comments also welcome. Thanks for your answers.
Try this code,
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length));
I hope this code help you..
The bulk insert that you do with the operation list will return a list of results (URIs I think, but it's been a few months since I did this), I believe you can get the ID you want from the first of these results
long rawContactId = ContentUris.parseId(rawContactUri);
After Applying the badge and receive the last segment you receive:
ContactsContract.RawContacts._ID
If you want to get Contact_id you should make this query:
(rowId - is the last segment you received before)
String[] projections = new String[]{ContactsContract.RawContacts.CONTACT_ID};
String select = ContactsContract.RawContacts._ID + "= ?";
String[] selectionArgs = new String[]{rowId};
Cursor cursor = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projections, select, selectionArgs, null);
String contactId = null;
if (cursor.getCount() == 0) {
Log.d("aaa","Couldn't find row: " + rowId);
return null;
}
if (cursor.moveToNext()) {
int columnIndex;
columnIndex = cursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID);
if (columnIndex == -1) {
Log.d("aaa","Couldn't get contact id");
} else {
contactId = cursor.getString(columnIndex);
}
}
cursor.close();
return contactId;

Algorithm of inserting android contact to SQL database

I need advise...
My app working with contacts, who have correspondence (SMS dialogs).
I have some difficulties with optimization getting process.
I decided realize that scheme:
On first launch read all "content://sms/inbox" and add unique value (broup by number of contact) to array new String [n.count()][4]. (fiedls: name, number, date, message and type)
Sort array as I want and transmit to main activity (or i can read db table directly there it doesn't matter)
Main activity class has procedure, which fill ListView (list.setAdapter) from receive data.
Everything works at the emulator perfectly, but when I trying setup at real device app catch fatal error.
So after aforesaid I have 2 quesions:
1. Why app is crashing? (any ideas)
2. How I can fix / rebuild my algorithm. Any pertinent criticism. I need function, which display in ListView contacts, "-" if contact does not have any incoming SMS, message of SMS if they exist.
Thanks.
below you can see procedures which insert and read data from db.
I will repeat, everything works at the emulator perfectly. It means db created, tables created and data insert, read and update. I public code "for a full picture".
public void Contact_to_db () {
dbHelper = new DBHelper(this);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query( Uri.parse( "content://sms/inbox" ), null, null, null, "DATE ASC");
int indexBody = cursor.getColumnIndex( SmsReceiver.BODY );
int indexAddr = cursor.getColumnIndex( SmsReceiver.ADDRESS );
int indexDate = cursor.getColumnIndex( SmsReceiver.DATE );
if ( indexBody < 0 || !cursor.moveToFirst() ) return;
String sender = "";
String number = "";
String message = "";
String type = "";
do {
sender = "";
message = "";
type = "";
number = cursor.getString( indexAddr );
if (getContactDisplayNameByNumber(cursor.getString( indexAddr )).equals(""))
sender = cursor.getString( indexAddr );
else
sender = getContactDisplayNameByNumber(cursor.getString( indexAddr ));
message = cursor.getString( indexBody );
SQLiteDatabase db_read = dbHelper.getReadableDatabase();
Cursor c = db_read.query(dbHelper.USER_TABLE, null, "number like " + number , null, null, null, null);
if (c.moveToFirst())
//fiend...
else {
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(sender);
boolean look = matcher.lookingAt();
if (look)
type = "1";
else
type = "0";
SQLiteDatabase db_whrite = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", sender);
cv.put("number", number);
cv.put("msg", message);
cv.put("date", cursor.getString( indexDate ));
cv.put("type", type);
db_whrite.insert(dbHelper.USER_TABLE, null, cv);
db_whrite.close();
}
c.close();
db_read.close();
}
}
while( cursor.moveToNext() );
cursor.close();
dbHelper.close();
}
read and fill...
public void UpdateTableRows() {
SMSDataCollection = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map = null;
String message = "";
SQLiteDatabase db_read = dbHelper.getReadableDatabase();
Cursor c = db_read.query(dbHelper.USER_TABLE, null, null, null, null, null, null);
prmax = c.getCount();
cnt = 0;
pbCount.setMax(prmax-1);
pbCount.setProgress(0);
int i = 0;
if (c.moveToFirst()) {
do {
message = c.getString(3);
if (!(message.equals(""))) {
if ((message.substring(0, 2).equals("SM")) && (message.length()>6)) {
try {
String CutMsg = message.substring(message.indexOf('|')+1, message.length());
String key = message.substring(2, message.indexOf('|'));
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(key);
boolean look = matcher.lookingAt();
if (look)
message = StringCryptor.decrypt(CutMsg, Integer.parseInt(key));
} catch (Exception e) {
e.printStackTrace(); }
} else
message = StringCryptor.decrypt(message, uPassword);
}
if (message.length() > 25)
message = message.substring(0, 24) + "...";
map = new HashMap<String,String>();
map.put(KEY_SENDER, c.getString(1));
map.put(KEY_NUMBER, c.getString(2));
map.put(KEY_MESS, message);
if (c.getString(4).equals("0"))
map.put(KEY_ICON, "person_icon_a");
else
map.put(KEY_ICON, "person_icon_f");
SMSDataCollection.add(map);
h.post(updateProgress);
} while (c.moveToNext());
}
c.close();
db_read.close();
dbHelper.close();
final BinderData bindingData = new BinderData(this,SMSDataCollection);
list.post(new Runnable(){
public void run() {
list = (ListView) findViewById(R.id.SMSList);
list.setAdapter(bindingData);
list.setEnabled(true);
//pbCount.setVisibility(View.GONE);
pbRound.setVisibility(View.GONE);
img_update.setVisibility(View.VISIBLE);
}
});
}

how to get local Contact account type?

I am trying to get local contact account type.Below is the code for it which works fine on Samsung devices but not working on sony, micromax etc.Please suggest where is the issue and to solve this
public void GetDefaultAccountNameAndType() {
String accountType = "";
String accountName = "";
long rawContactId = 0;
Uri rawContactUri = null;
ContentProviderResult[] results = null;
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).withValue(RawContacts.ACCOUNT_NAME, null).withValue(RawContacts.ACCOUNT_TYPE, null).build());
try {
results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch(Exception e) {
e.printStackTrace();
} finally {
ops.clear();
}
for (ContentProviderResult result : results) {
rawContactUri = result.uri;
rawContactId = ContentUris.parseId(rawContactUri);
}
Cursor c = getContentResolver().query(
RawContacts.CONTENT_URI
, new String[] {RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME}
, RawContacts._ID+"=?"
, new String[] {String.valueOf(rawContactId)}
, null);
if(c.moveToFirst()) {
if(!c.isAfterLast()) {
accountType = c.getString(c.getColumnIndex(RawContacts.ACCOUNT_TYPE));
accountName = c.getString(c.getColumnIndex(RawContacts.ACCOUNT_NAME));
}
}
getContentResolver().delete(rawContactUri, null, null);
c.close();
c = null;
System.out.println(accountType);
System.out.println(accountName);
//preference.setString("contactAccountType", accountType);
//preference.setString("contactAccountName", accountName);
}
TRY THIS, it works on sony but not in samsung. Don't know why is it so. I am also looking into the same issue.
/**
* Get All Account available in Phone and add into list
*/
private void getAllAccounts() {
int counter = 0;
final AccountManager accManager = AccountManager
.get(Activity.this);
final Account accounts[] = accManager.getAccounts();
for (int i = 0; i < accounts.length; i++) {
Log.i(TAG, "Name " + accounts[i].name + ", Type "
+ accounts[i].type);
}
}

Insert StatusUpdates into a specified contact, but always insert to a random contact

sample contacts:
_ID DISPLAY_NAME PHONE
1 contact1 11111111
2 contact2 22222222
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("22222222"));
Cursor c = this.getContentResolver().query(uri, new String[] {Data._ID}, null, null, null);
long profileId = 0;
if (c.moveToFirst())
{
profileId = c.getLong(0);
}
c.close();
c = null;
final ContentValues values = new ContentValues();
if (profileId > 0) {
values.put(StatusUpdates.DATA_ID, profileId);
values.put(StatusUpdates.STATUS, "HELLO WORLD!");
values.put(StatusUpdates.PROTOCOL, Im.PROTOCOL_CUSTOM);
values.put(StatusUpdates.CUSTOM_PROTOCOL, CUSTOM_IM_PROTOCOL);
values.put(StatusUpdates.PRESENCE, 4); //
values.put(StatusUpdates.STATUS_RES_PACKAGE, this.getPackageName());
values.put(StatusUpdates.STATUS_LABEL, R.string.label);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(StatusUpdates.CONTENT_URI)
.withValues(values).build());
try{
this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch(RemoteException e)
{Log.e...}
catch(OperationApplicationException e)
{Log.e...}
}
I'm trying to insert status to the specified contact "contact2", but it doesn't work correctly, and always insert to "contact1".
Please help me, many thanks.
from sample sync adapter example :
public static long lookupRawContact(ContentResolver resolver, String userId)
{
long authorId = 0;
final Cursor c =
resolver.query(RawContacts.CONTENT_URI, UserIdQuery.PROJECTION,
UserIdQuery.SELECTION, new String[] {userId},
null);
try {
if (c.moveToFirst()) {
authorId = c.getLong(UserIdQuery.COLUMN_ID);
}
} finally {
if (c != null) {
c.close();
}
}
return authorId;
}
This will return the correct profile ID or 0 if not found

Categories

Resources