Contact API problem with save datas Options - android

I'm facing a basic problem but i didn't find any tutorial in
order to help me...
I'm writing an application with sort of backup contact options. I want
that my applications works for android phones since 1.5 to 2.2
So i write a two implementation of ContactApi, one for 1.5, 1.6 and an
other for new api version.
Here is the list of problem I'm facing with.
With new api, nothing. All works fine, backing up contacts works well.
But with older api I'm not able to backing up some datas :
Email Datas (able to read, but not able to save)
IM datas (able to read, but not able to save)
Notes (able to read the first note, if many notes, I lost datas,
same things for backup)
Here is the code I'm using :
=======EMAIL=======
private ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.contentResolver.query(Contacts.ContactMethods.CONTENT_EMAIL_URI, null, Contacts.ContactMethods.PERSON_ID + " = ?", new String[] { id }, null);
Email email = null;
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
email = new Email();
email.setData(emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMe thods.DATA)));
email.setType(emailCur.getInt(emailCur.getColumnIndex(Contacts.ContactMetho ds.TYPE)));
email.setLabel(emailCur.getString(emailCur.getColumnIndex(Contacts.PeopleCo lumns.NAME)));
emails.add(email);
}
emailCur.close();
return emails;
}
private void saveEmailAddresses(ContentUris contactUri, List<Email> emailList, String id) {
if (emailList != null && emailList.size() > 0) {
ContentValues values = null;
ContentValues[] valueArray = new ContentValues[emailList.size()];
int i = 0;
for (Email email : emailList) {
values = new ContentValues();
values.put(Contacts.ContactMethods.PERSON_ID, id); //
values.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); //
values.put(Contacts.ContactMethods.DATA, email.getData()); //
values.put(Contacts.ContactMethods.TYPE, email.getType()); //
values.put(Contacts.PeopleColumns.NAME, email.getLabel()); //
valueArray[i] = values;
i++;
}
contentResolver.bulkInsert(Contacts.ContactMethods.CONTENT_EMAIL_URI, valueArray);
}
}
======== IM adress=============
private ArrayList<IM> getIM(Cursor cur, String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[] { id,
String.valueOf(Contacts.KIND_IM) };
Cursor imCur =
this.contentResolver.query(Contacts.ContactMethods.CONTENT_URI, null,
where, whereParameters, null);
IM im = null;
while (imCur.moveToNext()) {
try {
String imName =
imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
im = new IM();
im.setName(imName);
im.setType(imCur.getInt(imCur.getColumnIndex(Contacts.ContactMethodsColumns .TYPE)));
im.setProtocol(cur.getString(imCur.getColumnIndex(Contacts.ContactMethods.A UX_DATA)));
imList.add(im);
} catch (Exception e) {
Log.e(where, "Error im : ", e);
}
}
imCur.close();
return imList;
}
private void saveIM(List<IM> imList, String id) {
if (imList != null && imList.size() > 0) {
ContentValues values = null;
ContentValues[] valueArray = new ContentValues[imList.size()];
int i = 0;
for (IM im : imList) {
values = new ContentValues();
values.put(Contacts.ContactMethods.PERSON_ID, id); //
values.put(Contacts.ContactMethods.KIND, Contacts.KIND_IM); //
values.put(Contacts.ContactMethodsColumns.DATA, im.getName()); //
values.put(Contacts.ContactMethods.AUX_DATA,
ContactMethods.encodeCustomImProtocol(im.getProtocol())); //
values.put(Contacts.ContactMethodsColumns.TYPE, im.getType()); //
valueArray[i] = values;
i++;
}
contentResolver.bulkInsert(Contacts.ContactMethods.CONTENT_URI,
valueArray);
}
}
==========Notes =======
I have no idea how to get all notes ?
Can someone help me with this ?

public static HashMap Parse(String XML, String Tag, ArrayList<String> NodesList)
{
HashMap v = new HashMap();
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XML));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName(Tag);
nodeCount = nodeLst.getLength();
for (int s = 0; s < nodeCount; s++)
{
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt = (Element) fstNode;
for(String nodeName : NodesList)
{
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(nodeName);
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
try {
String NodeValue = ((Node) fstNm.item(0)).getNodeValue().toString().trim();
if(NodeValue !=null )
v.put(nodeName + s, NodeValue);
}
catch(Exception e) {
v.put(nodeName + s, "");
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
}
return v;
}

Related

Using IN() dynamically in SQLite

I have the query below:
public List<ListCoursesFilterModel> getListSubject(List<String> lstLang) {
StringBuilder langs = new StringBuilder();
StringBuilder questionMark = new StringBuilder();
for (int i = 0; i < lstLang.size(); i++) {
langs.append(",").append(lstLang.get(i).toLowerCase());
questionMark.append(",?");
}
String res = langs.substring(1, langs.length());
String qs = questionMark.substring(1, questionMark.length());
List<ListCoursesFilterModel> list = new ArrayList<>();
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query(
false,
"ShortMajorTBL",
null,
"langId IN(" + qs + ") AND identifier =?",
new String[]{res, "S300"},
null,
null,
null,
null
);
try {
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
ListCoursesFilterModel listCoursesFilterModel = new ListCoursesFilterModel();
listCoursesFilterModel.setSubject(cursor.getString(cursor.getColumnIndex("subject")));
listCoursesFilterModel.setLangId(cursor.getString(cursor.getColumnIndex("langId")));
listCoursesFilterModel.setIsSelected(cursor.getString(cursor.getColumnIndex("isSelected")));
listCoursesFilterModel.setIdentifier(cursor.getString(cursor.getColumnIndex("identifier")));
listCoursesFilterModel.setTitle(cursor.getString(cursor.getColumnIndex("title")));
listCoursesFilterModel.setCount(cursor.getInt(cursor.getColumnIndex("count")));
list.add(listCoursesFilterModel);
} while (cursor.moveToNext());
}
return list;
}
} catch (Exception ex) {
Throwable t = new Throwable(ex).fillInStackTrace();
FirebaseCrash.report(t);
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
lstLang when I have one value - for example en - it works and get results, but when I have multiple values - for example en,fr,ar - it doesn't show any result.
each of your values in the IN clause is a string.
Therefore, it has to singularily be escaped.
I.e.: 'en', 'fr', 'ar'.
So, have something like
...
qs = `'en', 'fr', 'ar'`; // somehow buid this dynamically
...
"langId IN(" + qs + ") AND identifier =?",
...

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

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

getting "null" as an address for a draft sms

I want to get (TO)address of sms saved as draft. I have tried query on canonical_addresses table it is giving me message "Failed to find provider info for canonical_addresses" in logs.
Then I have tried query on sms/draft table it is giving me null as an address.
What is wrong in my code? How should I get information about draft sms? I have searched but didn't get any solution.Plz suggest me some solution.
The way is to get the thread_id that corresponds to the draft message. Find the to address by using thread_id
public String getPhoneNumbersFromThreadID(Context ctx, String threadId)
{
//System.out.println(threadId);
String phoneList = "";
ArrayList<String> phoneCheckList = new ArrayList<String>();
if(thread2Phone.containsKey(threadId))
{
return thread2Phone.get(threadId);
}
if(threadId == null || threadId.equals(""))
{
return "No Name";
}
if(threadId.trim().length() == 0) return "No Name";
Cursor c = ctx.getContentResolver().query(SMSMainListActivity.Sms_CONTENT_URI,
null,
"thread_id = '" + threadId + "'", null, "date ASC");
if (c != null) {
try {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
String num = c.getString(c
.getColumnIndex("address"));
num = num.replaceAll(";", ",");
String[] thisNum = num.split(",");
for (int i=0; i<thisNum.length; i++)
{
phoneCheckList.add(formatNumber(thisNum[i])) ;
}
c.moveToNext();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
c.close();
}
}
try {
phoneCheckList = removeDuplicates(phoneCheckList);
Iterator it = phoneCheckList.iterator();
int i = 0;
while (it.hasNext()) {
String name = ""+it.next();
//System.out.println("Iterated "+name);
if(i==0)
phoneList = ""+name;
else
phoneList += ";"+name;
i++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
phoneCheckList.clear();
thread2Phone.put(threadId, phoneList);
return phoneList;
}

Get attachment from unread MMS messages

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?

Categories

Resources