Android Outgoing MMS get address - android

I'm trying to get the recipient address of an outgoing MMS using this code.
private String getAddressNumber(String id) {
String selectionAdd = new String("msg_id=" + id);
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
Cursor cAdd = getContentResolver().query(uriAddress, null,
selectionAdd, null, null);
String name = null;
if (cAdd.moveToFirst()) {
do {
String number = cAdd.getString(cAdd.getColumnIndex("address"));
if (number != null) {
try {
Long.parseLong(number.replace("-", ""));
name = number;
} catch (NumberFormatException nfe) {
if (name == null) {
name = number;
}
}
}
} while (cAdd.moveToNext());
}
if (cAdd != null) {
cAdd.close();
}
return name;
}
But It's returning "insert-address-token" instead of the actual address.

I met the same problem, and after some exploration, figured it out as following solution, mms is special as its outgoing message does not reflect the sent time in DATE field, also, the address field will be "insert-address-token", and TYPE will be 151, to get recipient number, we need to combine several table's query together. :
private static String getAddressNumberOfRecipient(int threadId) {
String selectionAdd = Telephony.Threads._ID + "=" + threadId;
String uriStr = MessageFormat.format("content://mms-sms/conversations/{0}/recipients", threadId);
Uri uriAddress = Uri.parse(uriStr);
String[] columns = {Telephony.Threads.RECIPIENT_IDS};
Cursor cAdd = context.getContentResolver().query(uriAddress, columns, selectionAdd, null, null);
String name = null;
if (cAdd.moveToFirst()) {
do {
name = cAdd.getString(cAdd.getColumnIndex(Telephony.Threads.RECIPIENT_IDS));
if (!TextUtils.isEmpty(name)) {
break;
}
}
while (cAdd.moveToNext());
}
if (cAdd != null) {
cAdd.close();
}
return TextUtils.isEmpty(name) ? "" : getCanonicalRecipient(Integer.parseInt(name.split(" ")[0]));
}
private static String getCanonicalRecipient(int recipientId) {
String selectionAdd = Telephony.CanonicalAddressesColumns._ID + "=" + recipientId;
String uriStr = MessageFormat.format("content://mms-sms/canonical-address/{0}", recipientId);
Uri uriAddress = Uri.parse(uriStr);
String[] columns = {Telephony.CanonicalAddressesColumns.ADDRESS};
Cursor cAdd = context.getContentResolver().query(uriAddress, columns, selectionAdd, null, null);
String name = null;
if (cAdd.moveToFirst()) {
do {
name = cAdd.getString(cAdd.getColumnIndex(Telephony.CanonicalAddressesColumns.ADDRESS));
if (!TextUtils.isEmpty(name)) {
break;
}
}
while (cAdd.moveToNext());
}
if (cAdd != null) {
cAdd.close();
}
return TextUtils.isEmpty(name) ? "" : filterPhoneNumber(name);
}

try this...
private String getAddressNumber(String id) {
String selectionAdd = new String("msg_id=" + id);
String uriStr = MessageFormat.format("content://mms/{0}/addr", id);
Uri uriAddress = Uri.parse(uriStr);
Cursor cursor = getContentResolver().query(uriAddress, null, selectionAdd, null, null);
String phoneNum = null;
if (cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex("address"));
if (number != null) {
boolean isNumberFormat = true;
try {
Long.parseLong(number.replace("-", ""));
phoneNum = number;
} catch (NumberFormatException e) { // ex) "insert-address-token"
// if (phoneNum == null) {
// phoneNum = number;
// }
isNumberFormat = false;
}
if (isNumberFormat)
break;
}
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return phoneNum;
}

Related

Contacts Update to DB Not working with ContentObserver

I am working with an Android application which shows the list of contacts in the phone like Whats-app. I am successful with getting the contacts to the Application database. When I try to update my DB when a contact is newly added/edited/deleted using Content Observer, I mainly face two problems
1. When Calls ,
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
I am getting wrong name. eg:- I edited Samuel's Contact no but checking the above code getting David's name.
when I try to get contact number by using the code,
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
I am getting error
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 402 rows, 41 columns.
03-01 17:16:56.546 3660-3660/com.xxxxxxxxx.xxxxx W/System.err: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Please Anybody help me to find the solution.
Here is my Code
public class ContactObserver extends ContentObserver {
Intent i;
private static final String TAG = "ObserverReceiver";
private Context context;
BaseActivity mBaseActivity;
public ContactObserver(Handler handler, BaseActivity context) {
super(handler);
this.mBaseActivity = context;
this.context = context;
}
public ContactObserver() {
super(null);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (!selfChange) {
try {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Log.d(TAG, "Observer has been started..");
// Contacts Cursor
final Cursor cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Check which contact is added or updated
if (cur != null) {
while (cur.moveToNext()) {
// Get contact added/updated timestamp but CONTACT_LAST_UPDATED_TIMESTAMP
// Get new/updated contact detail here
final String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
final String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
e.printStackTrace();
}
}
String finalContactNumber = contactNumber;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
List<Contacts> sContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getBySystemid(id);
Log.i("Contacts1+", new Gson().toJson(sContacts));
if (sContacts.size() > 0) {
for (Contacts mContacts : sContacts) {
String phone = finalContactNumber;
if (phone == null) {
phone = mContacts.getPhone();
}
Log.i("Contacts1+", contactName + " : " + phone);
if (phone != null && phone.length() > 0) {
phone = phone.replace(" ", "");
}
while (String.valueOf(phone.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < phone.length(); i++) {
num = num + phone.charAt(i);
}
phone = num;
}
if (phone.length() == 10) {
phone = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + phone;
}
if ((mContacts.getName() != contactName || mContacts.getPhone() != phone)) {
mContacts.setName(contactName);
if (!mContacts.getPhone().equalsIgnoreCase(phone)) {
mContacts.setPhone(phone);
mContacts.setIslisted("false");
}
if (mContacts.getPhone().equalsIgnoreCase(phone) || mContacts.getName().equalsIgnoreCase(contactName)) {
ContactDatabase.getDatabase(context)
.contactsDao()
.update(mContacts);
cur.close();
}
}
}
} else {
Contacts mContacts = new Contacts();
String contactNumber = null;
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null && contactNumber.length() > 0) {
contactNumber = contactNumber.replace(" ", "");
contactNumber = contactNumber.replace("-", "");
}
while (String.valueOf(contactNumber.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < contactNumber.length(); i++) {
num = num + contactNumber.charAt(i);
}
contactNumber = num;
}
if (contactNumber.length() == 10) {
contactNumber = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + contactNumber;
}
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
mContacts.setPhone(contactNumber);
mContacts.setName(contactName);
mContacts.setSystemid(id);
mContacts.setIslisted("false");
List<Contacts> cContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getbyPhone(contactNumber);
if (cContacts.size() == 0) {
ContactDatabase.getDatabase(context)
.contactsDao()
.insert(mContacts);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i = new Intent(context, ContactSynchService.class);
context.startService(i);
cur.close();
}
});
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSharedPreference(String key) {
SharedPreferences prefs = mBaseActivity.getSharedPreferences(AppConstants.SHARED_KEY, MODE_PRIVATE);
return prefs.getString(key, "DEFAULT");
}
}
I tried these links, but none of them could give a solution.
ContentObserver for contact update manually
ContentObserver not working in android
Android: ContentObserver not working in android 4.3
Any help will be appreciated. Thanks in Advance

fetching multiple contacts from phone book and display

The problem which i'm facing is I am not able to display the fetched value, as I have used a list view to display the values are not reaching it. This is my code snippet which fetches multiple contacts from phone book. Hope any1 help me solve it.
private void chooseContact() {
Intent phonebookIntent = new Intent("intent.action.INTERACTION_TOPMENU");
phonebookIntent.putExtra("additional", "phone-multi");
phonebookIntent.putExtra("maxRecipientCount", MAX_PICK_CONTACT);
phonebookIntent.putExtra("FromMMS", true);
startActivityForResult(phonebookIntent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_PICK_CONTACT) {
Uri contractData = data.getData();
ContactRetriever cr = new ContactRetriever(getApplicationContext(), contractData);
Person p = cr.getPerson();
if (p == null)
Toast.makeText(this, "Phone number not found!", Toast.LENGTH_SHORT).show();
else {
PersonManager.savePerson(p, getApplicationContext());
listContacts.setAdapter(new PersonAdapter(this, PersonManager.getSavedPersons(this)));
}
}
}
}}
And the Uri value is called and used in next below class
public class ContactRetriever {
private final String TAG = "ContactRetriever";
private ContentResolver cr;
private Context context;
private Uri contractData;
private String id;
public ContactRetriever(Context context,Uri contractData ) {
this.context = context;
this.cr = context.getContentResolver();
this.contractData = contractData;
}
public Person getPerson() {
String name = getName();
String num = getNumber();
if (name != null && num != null)
return new Person(getNumber(), getName());
else return null;
}
private String getNumber() {
String ret = null;
Cursor cId = cr.query(contractData, new String[]{ContactsContract.Contacts._ID}, null, null, null);
if (cId.moveToFirst()){
id = cId.getString(cId.getColumnIndex(ContactsContract.Contacts._ID));
Log.i(TAG + " IDs: ", id);
}
cId.close();
Cursor cNum = cr.query(contractData, null, null, null, null);
if (cNum.moveToNext()){
ret = cNum.getString(cNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(ret, TAG + " NUMBERS: ");
}
return ret;
}
private String getName() {
String ret = null;
Cursor c = cr.query(contractData, null, null, null, null);
if (c.moveToFirst())
ret = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
c.close();
Log.i(TAG + "NAMES: ", ret);
return ret;
}
}
Here is my working code for mine
//enter code here
private void getAllContacts() {
List<InviteContactInfo> inviteContactList = new ArrayList();
InviteContactInfo inviteContactInfo;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
inviteContactInfo = new InviteContactInfo();
inviteContactInfo.setContactName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
inviteContactInfo.setContactNumber(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
Bitmap photo =null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
inviteContactInfo.setContactImage(photo);
}
else
{
photo =BitmapFactory.decodeResource(getResources(), R.drawable.profilepic);;
inviteContactInfo.setContactImage(photo);
}
assert inputStream != null;
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
inviteContactList.add(inviteContactInfo);
}
}
InviteContactAdapter contactAdapter = new InviteContactAdapter(getApplicationContext(), inviteContactList);
recList.setLayoutManager(new LinearLayoutManager(this));
recList.setAdapter(contactAdapter);
}
}

Get the SMS/MMS thread_id from the phone number

I need to get the thread_id of the mms-sms/conversations Android content provider, this is what I have done so far:
public long findThreadIdFromPhoneNumber(Context context, PhoneNumber phoneNumber) {
Uri.Builder uriBuilder = Uri.withAppendedPath(Uri.parse(CONTENT_SMSMMS+"/"), "threadID").buildUpon();
// phoneNumber.msisdn() return the String phone number
uriBuilder.appendQueryParameter("recipient", phoneNumber.msisdn());
long threadId = -1L;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(
uriBuilder.build(),
new String[] { Contacts._ID },
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
threadId = cursor.getLong(0);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return threadId;
}
The problem is that this code create new threads in the content provider, and I don't need that, I just need to return the thread_id if the conversation exists and -1 if it do not exists.
I also tried this code:
public long findThreadIdFromPhoneNumber(Context context, PhoneNumber phoneNumber) {
long threadId = -1L;
Cursor cursor = null;
try {
if (context==null || context.getContentResolver()==null || phoneNumber==null || phoneNumber.msisdn()==null)
return threadId;
cursor = context.getContentResolver().query(
Uri.parse(CONTENT_SMSMMS_CONVERSATIONS),
// phoneNumber.msisdn() return the String phone number
null, "address='"+phoneNumber.msisdn()+"' ",
null, null
);
if (cursor != null && cursor.moveToFirst()) {
if (cursor.getColumnIndex("thread_id")>=0)
threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
}
} catch (Exception e) {
e.printStackTrace();
String number = (phoneNumber!=null && phoneNumber.msisdn()!=null) ? phoneNumber.msisdn() : "";
Logcat.e("Error during findThreadIdFromPhoneNumber for "+number+": "+e.getMessage(), e);
return threadId;
} finally {
if (cursor != null) {
cursor.close();
}
}
return threadId;
}
But this code give me an external NullPointerException in the ContentResolver in some phones, and it works in other:
java.lang.NullPointerException
at android.os.Parcel.readException(Parcel.java:1437)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:385)
at android.content.ContentResolver.query(ContentResolver.java:417)
at android.content.ContentResolver.query(ContentResolver.java:360)
at com.mypackage.android.sms.SmsMmsManager.findThreadIdFromPhoneNumber(SmsMmsManager.java:115)
Use this uri for fetching
ContentResolver cr = context.getContentResolver();
Cursor pCur = cr.query(
Uri.parse("content://mms-sms/canonical-addresses"), new String[]{"_id"},
"address" + " = ?",
new String[]{your_address}, null);
String thread_id = null;
if (pCur != null) {
if (pCur.getCount() != 0) {
pCur.moveToNext();
thread_id = pCur.getString(pCur.getColumnIndex("_id"));
}
pCur.close();
}
public MessageObjects getSms2(Context context , String number) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://sms/");
Cursor cursor = contentResolver.query(uri, null, "thread_id IS NOT NULL) GROUP BY (thread_id AND address=?", new String[]{number}, "date DESC");
String displayName;
String formattedDate = "";
String photoUri = null;
MessageObjects contct = new MessageObjects();
while (cursor.moveToNext()) {
displayName = "";
long key = cursor.getLong(cursor.getColumnIndex("_id"));
long threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
String address = cursor.getString(cursor.getColumnIndex("address")); // phone #
long date = cursor.getLong(cursor.getColumnIndex("date"));
Date callDayTime = new Date(Long.valueOf(date));
String body = cursor.getString(cursor.getColumnIndex("body"));
String person = cursor.getString(cursor.getColumnIndex("person"));
contct.setThreadId(threadId);
contct.setNumber(address);
contct.setTime(date);
contct.setMsg(body);
contct.setPerson(displayName);
}
cursor.close();
return contct;
}

Is there any solution to load phone messages in an activity?

I'd like to load messages from phone in my activity. I search for solution, but I can`t find any.
Use this :
private String SmsDetails(Application mContext) {
// TODO Auto-generated method stub
smsInbox = new ArrayList<Entry>();
final Uri SMS_Inbox = Uri.parse("content://sms/inbox");
String smsHistory = "";
try {
String sDirection = "1";
String sMessageType = "0";
String SMS_READ_COLUMN = "read";
String SORT_ORDER = " _id ASC";
int count = 0;
Cursor cursor;
int iLastIDRun = 0;
// "address = '+9180009'"
cursor = mContext.getContentResolver().query(
SMS_Inbox,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" },
" _id > " + String.valueOf(iLastIDRun), null,
SORT_ORDER);
sMessageType = "1";
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
String address = cursor.getString(2);
long timestamp = cursor.getLong(4);
String sBody = cursor.getString(5);
if (address.startsWith("1")) {
address = address.substring(1);
}
//store the required details
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
}
doCheckSmsHistory();
} catch (Exception e) {
e.printStackTrace();
}
return smsHistory;
}

How to query all the details of the Contact at once

EDIT:A list of what I consider important contact details:
1.NAME
2.PHONE NUMBER
3.EMAIL ADDRESS
4.WEBSITE
5.PHYSICAL ADDRESS
I would prefer to do this using a pre-fetched contactId...using only one cursor to get all of the data specified.I,preferably would like to find the right query to do this:
I would like to get all of the important details of a Contact at once,I am using the following code to do this:
public void getAllDataByContactId(int contactId)
{
Log.d(TAG, "Seriously scared it might not work");
String phoneNo="Phone disconnected";
String email="Email could not be delivered";
String website="Website 404";
String address="Number 13,Dark Street,Area 51,Bermuda Trianlge";
String name="Clint Eastwood";
int hasPhoneNumber;
String selection=ContactsContract.Data.CONTACT_ID+"=?";
String[] selectionArgs={String.valueOf(contactId)};
Cursor c=context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null,selection, selectionArgs,ContactsContract.Data.TIMES_CONTACTED);
if(c!=null && c.getCount()>0)
{
while(c.moveToNext())
{
phoneNo=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d(TAG, "Phone number: "+phoneNo);
email=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
Log.d(TAG, "Email: "+email);
website=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
Log.d(TAG, "Website :"+website);
address=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
name=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d(TAG, "Name :"+name);
}
}
}
However,although this does not throw an error it shows many rows consisting of an empty string interspresed with the actual values.How do I write a query that cuts out the noise?
I have tried this and this gets me all the values:
String selection=ContactsContract.Data.CONTACT_ID+"=? AND "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=? OR "+ContactsContract.Data.MIMETYPE+"=?";
String[] selectionArgs={String.valueOf(contactId),ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Too late to answer, but maybe it can help someone in the future.
My solution for this question with only one while cycle and query:
private void fetchContacts(ContentResolver contentResolver) {
if (contentResolver == null) return;
Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
if (cursor == null || cursor.getCount() <= 0) {
return;
}
String prevId = "";
String contactId = "";
PersonContact personContact = null;
while (cursor.moveToNext()) {
String company = "";
String columnName = cursor.getString(cursor.getColumnIndex("mimetype"));
if (columnName.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)) {
company = cursor.getString(cursor.getColumnIndex("data1"));
}
String email = "";
if (columnName.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
String phone = "";
if (columnName.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
phone = cursor.getString(cursor.getColumnIndex("data1"));
}
String first = "";
String last = "";
if (columnName.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
first = cursor.getString(cursor.getColumnIndex("data2"));
last = cursor.getString(cursor.getColumnIndex("data3"));
}
if (!prevId.equals(contactId)) {
if (!TextUtils.isEmpty(prevId)) {
addFilteredList(personContact);
allContacts.put(prevId, personContact);
}
prevId = contactId;
personContact = new PersonContact();
} else {
if (personContact != null) {
personContact.id = prevId;
if (TextUtils.isEmpty(personContact.company)) personContact.company = company;
if (TextUtils.isEmpty(personContact.firstName)) personContact.firstName = first;
if (TextUtils.isEmpty(personContact.lastName)) personContact.lastName = last;
if (!TextUtils.isEmpty(email) && personContact.emails.size() == 0) {
personContact.emails.add(email);
}
if (!TextUtils.isEmpty(phone) && personContact.phoneNumbers.size() == 0) {
personContact.phoneNumbers.add(phone);
}
}
}
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}
cursor.close();
}
As you can see, I used the prevId field, because cursor.moveToNext performs several times for one contact (once for first and last names, one for phone, etc.). After each iteration, I check the previous contact identifier with the current identifier and, if it is false, I update the fields in the personContact model.
May not be the best solution. But this is how I achieved it.
ArrayList<String> fnameList = new ArrayList<>();
ArrayList<String> lnameList = new ArrayList<>();
ArrayList<String> mnumList = new ArrayList<>();
ArrayList<String> hnumList = new ArrayList<>();
ArrayList<String> wnumList = new ArrayList<>();
ArrayList<String> mailList = new ArrayList<>();
final DynamoDBMapper dynamoDBMapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
final ContactsDO firstItem = new ContactsDO(); // Initialize the Notes Object
firstItem.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
// Query and loop for every phone number of the contact
Cursor pCur = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contact_id}, ContactsContract.CommonDataKinds.Phone.NUMBER);
int flag = 0;
assert pCur != null;
while (pCur.moveToNext()) {
String mobileNum = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
if (flag == 0) {
if(mobileNum!=null){
mnumList.add(mobileNum);}
} else if (flag == 1) {
if(mobileNum!=null){
hnumList.add(mobileNum);}
} else if (flag == 2) {
if(mobileNum!=null){
wnumList.add(mobileNum);}
}
flag++;
}
if(flag==1){
hnumList.add("");
wnumList.add("");
Log.e("Set","Both added");
}
if(flag==2){
wnumList.add("");
Log.e("Set","W added");
}
pCur.close();
}
}
}
cursor.close();
String MIME = ContactsContract.Data.MIMETYPE + "=?";
String[] params = new String[]{ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
final Cursor nameCur = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
MIME,
params,
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
assert nameCur != null;
int i = 0;
while (nameCur.moveToNext()){
String fname = "";
String lname = "";
fname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
lname = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
Log.e("In While","All the time");
if(fname!=null){
fnameList.add(fname);
Log.e("Put","Value Fname "+fname);}
if(lname!=null) {
lnameList.add(lname);
Log.e("Put","Value Lname "+lname);
}
if(fname==null){
fnameList.add(" ");
}
if(lname==null){
lnameList.add(" ");
}
i++;
}
nameCur.close();
Cursor cursorB = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursorB.getCount() > 0) {
while (cursorB.moveToNext()) {
// Query and loop for every email of the contact
String[] paramEmail = new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_TYPE};
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", paramEmail, ContactsContract.CommonDataKinds.Email.DISPLAY_NAME);
int j=0;
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
mailList.add(email);
Log.e("Email",email);
j++;
}
if(j==0){
mailList.add("");
Log.e("Email","Dummy Added");
}
emailCursor.close();
output.append("\n");
}
}cursorB.close();
Cursor cursorD = contentResolver.query(CONTENT_URI, null, null, null, null);
// Loop for every contact in the phone
if (cursorD.getCount() > 0) {
while (cursorD.moveToNext()) {
String contact_id = cursorD.getString(cursorD.getColumnIndex(_ID));
//for url
String newNoteUrl = "";
String whereName3 = ContactsContract.Data.MIMETYPE + " = ?";
String[] whereNameParams3 = new String[]{ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE};
ContentResolver contentResolverUrl = this.getContentResolver();
try {
Cursor cursorUrl = contentResolverUrl.query(ContactsContract.Data.CONTENT_URI, null, whereName3, new String[]{contact_id}, ContactsContract.CommonDataKinds.Website.URL);
while (cursorUrl.moveToNext()) {
newNoteUrl = cursorUrl.getString(cursorUrl.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
Log.e("URL",newNoteUrl);
}
Log.e("URL","Not Getting");
output.append("\nurl " + newNoteUrl);
firstItem.setUrl(newNoteUrl);
cursorUrl.close();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}cursorD.close();
Log.e("#######","##########################");
for(int m=0;m<fnameList.size();m++){
Log.e("Contact Val ",fnameList.get(m)+" , "+lnameList.get(m)+" , "+mnumList.get(m)+" , "+hnumList.get(m)+" , "+wnumList.get(m)+" , "+mailList.get(m));
ContactsDO item = new ContactsDO();
item.setUserId(AWSMobileClient.defaultMobileClient().getIdentityManager().getCachedUserID());
item.setFirstName(fnameList.get(m));
item.setLastName(lnameList.get(m));
item.setMobileNumber(mnumList.get(m));
item.setHomeNumber(hnumList.get(m));
item.setWorkNumber(wnumList.get(m));
item.setEmail(mailList.get(m));
try {
//saving to the database
dynamoDBMapper.save(item);
} catch (final AmazonClientException ex) {
Log.e(TAG, "Failed saving item : " + ex.getMessage(), ex);
}
}

Categories

Resources