Getting null exception when reading Android sent box - android

I have an assynctask that will read all the content in the conversation box and it works well
protected String doInBackground(String... params) {
Uri inboxURI = Uri.parse("content://sms/conversations");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(inboxURI, null, null, null, null);
c.moveToLast();
al = new ArrayList<MessageInfo>();
try{
for (int i = c.getCount(); i > 0; i--) {
MessageInfo mMessageInfo = new MessageInfo();
mMessageInfo.MessageText = c.getString(c.getColumnIndexOrThrow("snippet"));
mMessageInfo.ThreadId = c.getInt(c.getColumnIndex("thread_id"));
Uri uri = Uri.parse("content://sms/inbox");
String where = "thread_id=" + mMessageInfo.ThreadId;
Cursor Cursor = getContentResolver().query(uri, null, where,null, null);
startManagingCursor(Cursor);
//Cursor.moveToFirst();
String number = "";
String name = "";
if (Cursor.moveToFirst()) {
number = Cursor.getString(Cursor.getColumnIndexOrThrow("address")).toString();
name = GetNameAndNumber(Cursor, number, MessageBox.this);
Log.i("checkPoint","checkPoint-1 "+name);
}
else {
uri = Uri.parse("content://sms/sent");
where = "thread_id=" + mMessageInfo.ThreadId;
Cursor = GetCursor(uri, where, MessageBox.this);
if (Cursor.moveToFirst()) {
number = Cursor.getString(Cursor.getColumnIndexOrThrow("address")).toString();
name = GetNameAndNumber(Cursor, number, MessageBox.this);
Log.i("checkPoint","checkPoint-2 "+name);
}Cursor.close();
}
if (name.length() > 0) {
mMessageInfo.Name = name;
} else {
mMessageInfo.Name = number;
}
mMessageInfo.Number = number;
Log.i("name",name);
Log.i("number",number);
Log.i("mMessageInfo.ThreadId ",""+mMessageInfo.ThreadId );
al.add(mMessageInfo);
c.moveToPrevious();
}c.close();
}catch(Exception x){x.printStackTrace();}
return "Executed";
}
But if my app writes to content://sms/sent the above code gives null exception but the stock messaging app can read it well.
This is the method how I update my sent items
void sentBox(){
ContentValues values = new ContentValues();
values.put("address", number);
values.put("body", msgBox.getText().toString());
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
finish();
}
To be specific I cannot get the address of the message in the sent items.. below returns null exception.. I think there is something to do with my URI.
if (Cursor.moveToFirst())
number = Cursor.getString(Cursor.getColumnIndexOrThrow("address")).toString();
Can someone give me hint why it can't read if I write/update my sent box that way?

I've Manage to fix the problem. It was another method which is writing to sent box using the message ID where there is another method writing to sent box using the address..
protected String doInBackground(String... params) {
al = new ArrayList<MessageInfo>();
String number = "";
String name = "";
Uri conversationURI = Uri.parse("content://sms/conversations");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(conversationURI, null, null, null, null);
c.moveToLast();
for (int i = c.getCount(); i > 0; i--) {
MessageInfo mMessageInfo = new MessageInfo();
mMessageInfo.MessageText = c.getString(c.getColumnIndexOrThrow("snippet"));
mMessageInfo.ThreadId = c.getInt(c.getColumnIndex("thread_id"));
try{
Uri message = Uri.parse("content://sms/inbox");
ContentResolver cr_ = getContentResolver();
String where_ = "thread_id=" + mMessageInfo.ThreadId;
Cursor c_ = cr_.query(message, null, where_, null, null);
startManagingCursor(c_);
if (c_.moveToFirst() && c_ != null) {
number = c_.getString(c_.getColumnIndexOrThrow("address"));
name = GetNameAndNumber(c_, number, MessageBox.this);
}else{
Uri _message_ = Uri.parse("content://sms/sent");
ContentResolver _cr_ = getContentResolver();
String _where_ = "thread_id=" + mMessageInfo.ThreadId;
Cursor _c_ = _cr_.query(_message_, null, _where_, null, null);
if (_c_.moveToFirst() && _c_ != null) {
number = _c_.getString(_c_.getColumnIndexOrThrow("address"));
name = GetNameAndNumber(_c_, reformatNumber(number), MessageBox.this);
}
}
}catch(Exception x){x.printStackTrace();}
if (name.length() > 0) {
mMessageInfo.Name = name;
} else {
mMessageInfo.Name = number;
}
mMessageInfo.Number = number;
al.add(mMessageInfo);
c.moveToPrevious();
}c.close();
return null;
}
Changed this FROM:
void sentBox(){
ContentValues values = new ContentValues();
values.put("thread_id", getIntent().getExtras().getInt("ID"));
values.put("body", mMessageEditText.getText().toString());
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
}
TO:
void sentBox(){
ContentValues values = new ContentValues();
values.put("address", getIntent().getExtras().getString("number"));
values.put("body", mMessageEditText.getText().toString());
}

Related

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;
}

How do i get the SMS Sender Contact (Person) saved name using "content://sms/inbox"

In my App i want to retrieve the SMS sender saved Name using below code but it always return null. Please suggest me whats the convenient way to get the sender name.
Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
android.util.Log.i("COLUMNS", Arrays.toString(c.getColumnNames()));
try {
if(c.getCount()>0)
{
while (c.moveToNext()){
Log.d("SMSss", "Contact : "+c.getString(2)+"\n"
+"msg : "+c.getString(11)+"\n"
+"ID : "+c.getString(0)+"\n"
+"Person : "+c.getString(3));
}
}
} catch (Exception e) {
Log.d("mmmmmmmmm"," "+ e.getStackTrace());
}
i am using following permission in menifest
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
Please suggest me how to get. Thanks in advance.
By this way you can get the saved contact name from inbox..
call the method getAllSms() to get the details..
public void getAllSms() {
Uri message = Uri.parse("content://sms/");
ContentResolver cr = getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
Log.d("SMSss",
"Contact number : "
+ c.getString(c
.getColumnIndexOrThrow("address"))
+ "\n"
+ "msg : "
+ c.getColumnIndexOrThrow("body")
+ "\n"
+ "ID : "
+ c.getString(c.getColumnIndexOrThrow("_id"))
+ "\n"
+ "Person : "
+ getContactName(
getApplicationContext(),
c.getString(c
.getColumnIndexOrThrow("address"))));
c.moveToNext();
}
}
c.close();
}
public String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri,
new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor
.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
Uri uriInbox = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriInbox, null, null, null, null);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
String name = null;
String phone = "";
String _id = c.getString(c.getColumnIndexOrThrow("_id"));
String thread_id = c.getString(c.getColumnIndexOrThrow("thread_id"));
String msg = c.getString(c.getColumnIndexOrThrow("body"));
String type = c.getString(c.getColumnIndexOrThrow("type"));
String timestamp = c.getString(c.getColumnIndexOrThrow("date"));
phone = c.getString(c.getColumnIndexOrThrow("address"));
name = Function.getContactbyPhoneNumber(getApplicationContext(), c.getString(c.getColumnIndexOrThrow("address")));
c.moveToNext();
}
}
c.close();
Finally your getContactbyPhoneNumber method:
public String getContactbyPhoneNumber(Context c, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME};
Cursor cursor = c.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) {
return phoneNumber;
}else {
String name = phoneNumber;
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
} finally {
cursor.close();
}
return name;
}
}
Courtesy: http://www.androstock.com/tutorials/create-sms-app-android-android-studio-part-2.html

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);
}
}

Getting multiple phone numbers from selected contact

I am developing an application in which i am using startactivity result and accessing default android phonebook in my application, after that on selecting one contact i am getting name, one phone number of the selected contact. I want to retrieve multiple phone numbers if any of the contacts have it and type of phone numbers like work, mobile etc. please help me in this, Any help would be appreciated.
try this as this works for me:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, AppConstants.PICK_CONTACT);
then in onActivityResult do the following:
Cursor cursor = null;
String phoneNumber = "", primaryMobile = "";
List<String> allNumbers = new ArrayList<String>();
int contactIdColumnId = 0, phoneColumnID = 0, nameColumnID = 0;
try {
Uri result = data.getData();
Utils.printLog(TAG, result.toString());
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
contactIdColumnId = cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
phoneColumnID = cursor.getColumnIndex(Phone.DATA);
nameColumnID = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
idContactBook = cursor.getString(contactIdColumnId);
displayName = cursor.getString(nameColumnID);
phoneNumber = cursor.getString(phoneColumnID);
if (phoneNumber.length() == 0)
continue;
int type = cursor.getInt(cursor.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_MOBILE && primaryMobile.equals(""))
primaryMobile = phoneNumber;
allNumbers.add(phoneNumber);
cursor.moveToNext();
}
} else {
// no results actions
}
} catch (Exception e) {
// error actions
} finally {
if (cursor != null) {
cursor.close();
}
}
try this
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);

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