Related
I got name and contact id from android "my" contact by using this method
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
}
}
How to get phone number of the device too?
Add following permission in manifest.
<uses-permission android:name="android.permission.READ_CONTACTS" />
Use Following code to get "Me" contact.
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath( ContactsContract.Profile.CONTENT_URI,ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
//Don't select anything here null will return all available fields
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
ArrayList<String> DataArray = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//here where you get your data and its type
TypeName=cursor.getString(ProfileQuery.ADDRESS);//this will give you field name
Data=cursor.getString(ProfileQuery.NUMBER);//this will give you field data
cursor.moveToNext();
}
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.ADDRESS ,
ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Organization.DATA3,
};
int ADDRESS = 0;
int NUMBER = 1;
}
Try this:
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
And in manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
This is the proper way of doing it
1) call the intent
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
if(intent.resolveActivity(getActivity().getPackageManager()) != null) {
getParentFragment().startActivityForResult(intent, CONTACT_REQUEST_CODE);
}
2) Implement onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CONTACT_REQUEST_CODE) {
uriContact = data.getData();
// replaceAll("\\D", "") : Remove everything that is not a digit
String number = retrieveContactNumber();
if (Connectivity.isConnected(getActivity())) {
if (number != null) {
String contact_number = number.replaceAll("\\D", "");
}
}
}
}
}
3) implement retrieveContactNumber()
private String retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
// Using the contact ID to get contact phone number
Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
return contactNumber;
}
4) Enjoy :)
Try this...
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
namee = c.getString(1);
if(Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",new String[] { contact_id }, null);
while (pCur.moveToNext()) {
String noo = pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
}
}
}
I think you should use ContactsContract.CommonDataKinds.Phone.CONTENT_URI and there is column called ContactsContract.CommonDataKinds.Phone.NUMBER using which you may get contact number.
Have a look this code
public ArrayList<String> getContactList(){
ArrayList<String> list= new ArrayList<String>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] columns = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = getContentResolver().query(uri, columns, null, null, null);
int _nameIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _numberIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String name = people.getString(_nameIndex);
String number = people.getString(_numberIndex);
list.add(name+" :"+number);
// Do work...
} while (people.moveToNext());
return list;
}
This worked for me.
String[] columnNames = new String[] { Phone._ID,
Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor c = LoginActivity.this.getContentResolver().query(
ContactsContract.Profile.CONTENT_URI, columnNames,
null, null, null);
int count = c.getCount();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
for (int j = 0; j < columnNames.length; j++) {
contact_id = c.getString(0);
name = c.getString(1);
number= c.getString(2);
}
}
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());
}
I have implemented the code to get sms from inbox to my app.It gets all messages.But I want to load messages from specific number.I followed the tutorial from [Read all SMS from a particular sender it shows empty view.I worked out this code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox);
ListView list = (ListView) findViewById(R.id.listView1);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
}
public List<String> getSMS() {
List<String> sms = new ArrayList<String>();
// StringBuilder smsBuilder = new StringBuilder();
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_ALL = "content://sms/";
try {
Uri uri = Uri.parse(SMS_URI_INBOX);
String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };
Cursor cur = getContentResolver().query(uri, projection, "address='5558'", null, null);
if (cur.moveToFirst()) {
int index_Address = cur.getColumnIndex("address");
int index_Person = cur.getColumnIndex("person");
int index_Body = cur.getColumnIndex("body");
int index_Date = cur.getColumnIndex("date");
int index_Type = cur.getColumnIndex("type");
do {
String strAddress = cur.getString(index_Address);
int intPerson = cur.getInt(index_Person);
String strbody = cur.getString(index_Body);
long longDate = cur.getLong(index_Date);
int int_Type = cur.getInt(index_Type);
sms.add("Number: " + strAddress + " .Message: " + strbody);
// smsBuilder.append("[ ");
// smsBuilder.append(strAddress + ", ");
// smsBuilder.append(intPerson + ", ");
// smsBuilder.append(strbody + ", ");
// smsBuilder.append(longDate + ", ");
//smsBuilder.append(int_Type);
// smsBuilder.append(" ]\n\n");
} while (cur.moveToNext());
if (!cur.isClosed()) {
cur.close();
cur = null;
}
else {
// smsBuilder.append("no result!");
} // end if
}} catch (SQLiteException ex) {
Log.d("SQLiteException", ex.getMessage());
}
return sms;
}
I passed address as my another emulator.If I gave null replacing address field of getContentResolver()it will load all sms in inbox.Can anyone help me where I have to modify ?
Use following code,
Uri uri = Uri.parse("content://sms/");
ContentResolver contentResolver = getContentResolver();
String phoneNumber = "+911234567890";
String sms = "address='"+ phoneNumber + "'";
Cursor cursor = contentResolver.query(uri, new String[] { "_id", "body" }, sms, null, null);
System.out.println ( cursor.getCount() );
while (cursor.moveToNext())
{
String strbody = cursor.getString( cursor.getColumnIndex("body") );
System.out.println ( strbody );
}
Following permission is required,
<uses-permission android:name="android.permission.READ_SMS"/>
100% working code :
String[] projection = new String[] { "_id", "thread_id","address", "person", "body", "date", "type" };
Uri uri = Uri.parse("content://sms/");
Cursor c = cr.query(uri, projection,"address='9876543210'",null, "date desc");
int totalSMS = 0;
if (c != null) {
totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int j = 0; j < totalSMS; j++) {
String id = c.getString(c.getColumnIndexOrThrow(Telephony.Sms._ID));
String thread_id = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.THREAD_ID));
String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE));
String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS));
String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY));
String type;
switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(Telephony.Sms.TYPE)))) {
case Telephony.Sms.MESSAGE_TYPE_INBOX:
type = "inbox";
messageList.add(new Message(id, thread_id, number, body, smsDate, type));
break;
case Telephony.Sms.MESSAGE_TYPE_SENT:
type = "sent";
messageList.add(new Message(id, thread_id, number, body, smsDate, type));
break;
case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
break;
default:
break;
}
c.moveToNext();
}
}
c.close();
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);
}
}
I would like to get attachment from unread MMS messages, but the codes I have doesn't allow me to do so. How do I go about doing that?
Codes modified from here:
private void checkMMSMessages(){
// Create string arrays to store the queries later on
String[] columns = null;
String[] values = null;
// Calls the ContentResolver to query for columns with URI "content:mms"
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, null, null, null);
if(curPdu.moveToNext()){
//String read = curRead.getString(curRead.getColumnIndex("read"));
// Gets ID of message
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
// Gets thread ID of message
String thread_id = curPdu.getString(curPdu.getColumnIndex("thread_id"));
// Gets subject of message (if any)
String subject = curPdu.getString(curPdu.getColumnIndex("sub"));
// Gets date of message
String date = curPdu.getString(curPdu.getColumnIndex("date"));
String selectionAddr = new String ("msg_id = '" + id + "'");
Uri uriAddr = Uri.parse ("content://mms/" + id + "/addr");
Cursor curAddr = getContentResolver().query(uriAddr, null, null, null, null);
if(curAddr.moveToNext()){
String contact_id = curAddr.getString (curAddr.getColumnIndex ("contact_id"));
String address = curAddr.getString (curAddr.getColumnIndex ("address"));
String selectionPart = new String ("mid = '" + id + "'");
Cursor curPart = getContentResolver ().query(Uri.parse ("content://mms/part"), null, null, null, null);
//Cursor curPart = context.getContentResolver ().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
String contact_idd = curPart.getString(0);
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
//Toast.makeText(getApplicationContext(), "Retrieved MMS attachment", Toast.LENGTH_LONG);
}
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
Figured out myself, the codes are as follows:
private void checkMMSMessages() {
String[] columns = null;
String[] values = null;
String read = "read = 0";
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, read, null, null);
if(curPdu.moveToNext()){
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
Cursor curPart = getContentResolver().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
I think he asked how to retrieve the attachment from the server, as it is written UNREAD mms... If you have the column ct_l how to get the data from that internet address?