Fetching images from MMS gives wrong MMS - android

My app is trying to fetch SMS and MMS from the device and store it in a database. I have tried this code: How to Read MMS Data in Android? This is working fine, but the problem is getting the wrong MMS image. This happens in the scenario when I send a new MMS , while backing up the MMS.
Here is my code:
// To get text content from mms..
public ArrayList<String> getMmsTextContent(String mmsId) {
String body = null;
ArrayList<String> arlMMS = new ArrayList<String>();
String selectionPart = "mid=" + mmsId;
Uri uri = Uri.parse("content://mms/part");
Cursor cursor = getContentResolver().query(uri, null, selectionPart,
null, null);
if (cursor.moveToFirst()) {
do {
String partId = cursor.getString(cursor.getColumnIndex("_id"));
String type = cursor.getString(cursor.getColumnIndex("ct"));
if ("text/plain".equals(type)) {
String data = cursor.getString(cursor
.getColumnIndex("_data"));
if (data != null) {
// implementation of this method below
body = getMmsText(partId);
arlMMS.add(body);
} else {
body = cursor.getString(cursor.getColumnIndex("text"));
arlMMS.add(body);
}
}
} while (cursor.moveToNext());
return arlMMS;
}
return null;
}
// To get the text
private String getMmsText(String id) {
Uri partURI = Uri.parse("content://mms/part/" + id);
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
is = getContentResolver().openInputStream(partURI);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String temp = reader.readLine();
while (temp != null) {
sb.append(temp);
temp = reader.readLine();
}
}
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
// To get the mms..
public ArrayList<Bitmap> getMms(String mmsId) {
Bitmap bitmap = null;
ArrayList<Bitmap> arlBitmap = new ArrayList<Bitmap>();
String selectionPart = "mid=" + mmsId;
Uri uri = Uri.parse("content://mms/part");
Cursor cPart = getContentResolver().query(uri, null, selectionPart,
null, null);
if (cPart.moveToFirst()) {
do {
String partId = cPart.getString(cPart.getColumnIndex("_id"));
String type = cPart.getString(cPart.getColumnIndex("ct"));
if ("image/jpeg".equals(type) || "image/bmp".equals(type)
|| "image/gif".equals(type) || "image/jpg".equals(type)
|| "image/png".equals(type)) {
bitmap = getMmsImage(partId);
arlBitmap.add(bitmap);
}
} while (cPart.moveToNext());
return arlBitmap;
}
return arlBitmap;
}
// To get bitmap from mms
private Bitmap getMmsImage(String _id) {
Uri partURI = Uri.parse("content://mms/part/" + _id);
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return bitmap;
}
}
Please help me.

Running two threads at a time one is Backup images and second one is retrieving images from sqlite . Change two folders different can eliminate this problem

Related

Android contact book overwrites EXIF image data

In my app I'm trying to add an EXIF attribute to a contact photo when I add it to either a new or existing contact. This is so I can later check to see if it was My_App that changed the photo. I add the EXIF data like this:
private void addPhotoToExistingContact(long rawContactId, byte[] photoByteArray) {
if (photoByteArray != null) {
try {
photoByteArray = addExifDataToContactPhoto(photoByteArray);
} catch (IOException e) {
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray);
context.getContentResolver().insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}
private byte[] addExifDataToContactPhoto(byte[] photoByteArray) throws IOException {
// Convert to temp file
File file = new File(context.getCacheDir(), "contact_photo_exif_temp_file.jpg");
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(file.getAbsoluteFile());
fos.write(photoByteArray);
fos.close();
// Add EXIF data
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
exif.setAttribute(MY_EXIF_TAG, MY_EXIF_VALUE);
exif.saveAttributes();
// Convert back to byte[]
byte[] photoByteArrayWithExifData = FileUtils.readFileToByteArray(file);
// Delete temp file
file.delete();
return photoByteArrayWithExifData;
}
My check for EXIF data (done at a later time) is as follows:
private boolean shouldReplaceContactPhoto(long contactId) {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?",
new String[] { ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE, String.valueOf(contactId) },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
long photoId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.PHOTO_ID));
if (photoId == 0) {
cursor.close();
return true;
}
else {
// Read EXIF data to check if photo is a My_App photo
File contactPhotoTempFile = getExistingContactImageFile(contactId);
if (contactPhotoTempFile != null) {
try {
ExifInterface exif = new ExifInterface(contactPhotoTempFile.getAbsolutePath());
String swopTag = exif.getAttribute(MY_EXIF_TAG);
// Temporary image, so delete it when we're done reading EXIF data
contactPhotoTempFile.delete();
cursor.close();
// If tag is null, the photo came from a different source - return 'true'
// so it is not replaced.
return myTag != null;
} catch (IOException e) {
e.printStackTrace();
// Temporary image, so delete it when we're done reading EXIF data
contactPhotoTempFile.delete();
}
}
cursor.close();
return true;
}
}
cursor.close();
}
return true;
}
private File getExistingContactImageFile(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
byte[] imageBytes;
try {
AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
InputStream inputStream = fd.createInputStream();
imageBytes = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
return null;
}
if (imageBytes == null) {
return null;
}
File file = new File(context.getCacheDir(), "contact_photo_temp_file.jpg");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
fos.write(imageBytes);
fos.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return file;
}
I've added break points and log statements and I'm almost 100% positive that the attribute is being written, but when I read the data, the property is missing. I also noticed that the orientation attribute is changed from 1 to 0 as well, which leads me to believe that Android is overwriting the EXIF data.
Is this the case, or am I doing something incorrectly? Any help at all is extremely appreciated!

Not able to get file path when using GoogleDrive in android version 4.4.2

In my android application, i have used google drive to pick images and files to my application, it works perfectly in all API version except 4.4.2, whenever i tried to pick image or file i can get the file name but not able to get file path, it always returns empty path
My code :
// Get real path from Google Drive
public String getPathfromGoogleDrive(Intent data, Uri contentURI) {
if (contentURI == null) {
return null;
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
String mCurrentPhotoPath = new String();
Cursor cursor = null;
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
LogUtil.d("currentapiVersion" + currentapiVersion);
if (currentapiVersion == 19) {
String wholeID = DocumentsContract.getDocumentId(contentURI);
// Split at colon, use second item in the array
String id = wholeID.split(";")[0];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = getActivity().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
filePathColumn, sel, new String[] { id }, null);
LogUtil.d("Cursor Count" + cursor.getCount());
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
}
}
My Intent :
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion == 19) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
String strType = "*/*";
intent.setDataAndType(null, strType);
startActivityForResult(intent, Gallery);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setPackage("com.google.android.apps.docs");
String strType = "*/*";
intent.setDataAndType(null, strType);
startActivityForResult(intent, Gallery);
}
Please correct me if i have did any mistake
Thanks in advance
Instead of getting file real path, we can use input stream as like below
Bitmap bitmap = null;
InputStream input = null;
try {
input = getActivity().getContentResolver().openInputStream(selectedImageURI);
bitmap = BitmapFactory.decodeStream(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
To Get File from drive and write that into locale(sd card)
sourceuri - your cnontent uri
destination - path where you want to save in sd card
public boolean savefile(String name, Uri sourceuri, String destination)
throws IOException {
// String sourceFilename = sourceuri.getPath();
int originalsize = 0;
InputStream input = null;
try {
input = getContentResolver().openInputStream(sourceuri);
Log.Logger().finest("input in profileview Activity" + input);
} catch (FileNotFoundException e) {
e.printStackTrace();
filenotfoundexecption = true;
}
try {
originalsize = input.available();
Log.Logger().finest(
"Profile view activity originalsize" + originalsize);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(input);
bos = new BufferedOutputStream(new FileOutputStream(
destination, false));
byte[] buf = new byte[originalsize];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
} catch (IOException e) {
Mint.logException(e);
filenotfoundexecption = true;
return false;
}
} catch (NullPointerException e1) {
Mint.logException(e1);
filenotfoundexecption = true;
}
/*
* String[] cmd = new String[] { "logcat", "-f", GridViewDemo_LOGPATH,
* "-v", "time", "ActivityManager:W", "myapp:D" };
*
* Runtime.getRuntime().exec(cmd);
*/
return true;
}

How can I make this MP3 work in the background?

This is the utils code, the MP3 work only when the app is open, once you click in the back or the home button it stops.
How can I put it in the background?
public class Util {
public ArrayList<Contact> getAllContact(Context context) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
if(cursor != null) {
while (cursor.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String aaaa = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CUSTOM_RINGTONE));
if (phone!=null && phone.equals("1")) {
Contact contact = new Contact();
contact.setId(Integer.parseInt(id));
contact.setName(name);
contacts.add(contact);
}
}
}
cursor.close();
return contacts;
}
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
// TODO: handle exception
// Log.e("LOG", "Error: " + e.getMessage());
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
public void assignRingtoneToContact(Context context, SongInfo info,Contact contact) {
File dir =null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.IS_RINGTONE
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
Uri fullUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, fullUri.toString());
}
}
cursor.close();
if(!isRingTone){
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri oldUri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
ContentValues Newvalues = new ContentValues();
Uri newUri;
String uriString;
context.getContentResolver().delete(oldUri, MediaStore.MediaColumns.DATA + "=\"" + file.getAbsolutePath() + "\"", null);
Newvalues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
Newvalues.put(MediaStore.MediaColumns.TITLE, info.getName());
Newvalues.put(MediaStore.MediaColumns.SIZE, file.length());
Newvalues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Newvalues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
newUri = context.getContentResolver().insert(uri, Newvalues);
uriString = newUri.toString();
values.put(ContactsContract.Contacts.CUSTOM_RINGTONE, uriString);
Log.i("LOG", "uriString: " + uriString);
}
}
int count = context.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values,ContactsContract.Contacts._ID +" = "+contact.getId(), null);
// Log.i("LOG", "Update: " + count);
}
#SuppressWarnings("deprecation")
public Uri getContactContentUri() {
if(Build.VERSION.SDK_INT >= 5){
return ContactsContract.Contacts.CONTENT_URI;
}
else{
return Contacts.People.CONTENT_URI;
}
}
}
try using MediaPlayer, it has many options
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, ringtone);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
You need to develop player as a service, refer this ,
official docs

File not found exception while reading email attachment file from my app in Android

Hi I am trying to read an email attachment from my app.
When I click on the email attachment it opens my app and in that I am trying to read the content of the file using the following code
Intent CallingIntent = getIntent();
Uri data = CallingIntent.getData();
final String scheme = data.getScheme();
if(ContentResolver.SCHEME_CONTENT.equals(scheme))
{
ContentResolver cr = getApplicationContext().getContentResolver();
InputStream is;
try
{
is = cr.openInputStream(data);
if(is == null)
{
return;
}
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str;
if (is!=null)
{
while ((str = reader.readLine()) != null)
{
buf.append(str);
}
}
is.close();
Toast.makeText(getApplicationContext(), buf, Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and when try to open the file using the statement is = cr.openInputStream(data); it gives me an exceptioniFileNotFoundException
Can any suggest how can I accomplish this such in my app I am able to read the content of the attachment without downloading it.
You need to extract real path of file from this URI. This function will return you the path.
// replace this
is = cr.openInputStream(data)
//with
is = cr.openInputStream(getPath(data))
public static String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = BigNoteActivity.instance.getContentResolver().query(
uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

I want mms number,sent/received, body and attachment details from MMS db in android... How to do that?

I am using "content://mms" Content resolver and getting mms database. How to get number,sent/received, body and attachment details from that?
This link actually helped me a lot:
Try this post: How to Read MMS Data in Android?
Hope this helps you little bit..:)
I also tried to get some info by using this code:
private String getMmsText(String id) {
Uri partURI = Uri.parse("content://mms/part/" + id);
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
is = getContentResolver().openInputStream(partURI);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader reader = new BufferedReader(isr);
String temp = reader.readLine();
while (temp != null) {
sb.append(temp);
temp = reader.readLine();
}
}
} catch (IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
// Main Text
Cursor cursor = getContentResolver().query(uri, null, selectionPart,
null, null);
if (cursor.moveToFirst()) {
do {
String partId = cursor.getString(cursor.getColumnIndex("_id"));
String type = cursor.getString(cursor.getColumnIndex("ct"));
if ("text/plain".equals(type)) {
String data = cursor.getString(cursor
.getColumnIndex("_data"));
if (data != null) {
// implementation of this method below
body = getMmsText(partId);
} else {
body = cursor.getString(cursor.getColumnIndex("text"));
}
}
} while (cursor.moveToNext());
}
cursor.close();

Categories

Resources