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
Related
The below shows the way how I tried and it gives me NulllPointException: Uri While selecting a PDF file from the recent files folder in Android 11.
Please let me know How to get pdf file path from recent folder
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
//todo when permission is granted
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
} else {
//request for the permission
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] mimetypes = {"image/*", "application/*"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, path);
startActivityForResult(intent, REQ_PDF);
}
}
});
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
try {
if (requestCode == REQ_PDF && resultCode == RESULT_OK && data != null) {
path = data.getData();
inputStream = this.getContentResolver().openInputStream(path);
byte[] pdfInBytes = new byte[inputStream.available()];
inputStream.read(pdfInBytes);
// Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
String encodedCode = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
filePath = PathUtil.getPathFromUri(this, path);
// filePath= FileUtils.getPath(this,path);
if (filePath == null) {
// Toast.makeText(this, "null", Toast.LENGTH_SHORT).show();
SharedPrefMannager.showAlertDialog(InvoiceGenerationActivity.this, "Alert!", "Please select a file from internal storage", true);
} else {
file = new File(filePath);
file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
}
tv_attachFile.setText("Change File");
tv_fileLocation.setVisibility(View.VISIBLE);
tv_fileLocation.setText(filePath);
//Toast.makeText(getContext(), encodedCode, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(InvoiceGenerationActivity.this, "Something went wrong " + e, Toast.LENGTH_SHORT).show();
}
}
public class PathUtil
{
private static Uri contentUri = null;
#SuppressLint("NewApi")
public static String getPathFromUri(final Context context, final Uri uri) {
// check here to is it KITKAT or new version
final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
//return getPathFromExtSD(split);
/* String fullPath =Environment.getExternalStorageState() + "/" + split[1];
if (fullPath != "") {
return fullPath;
} else {
return null;
}*/
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.parseLong(id)); //public
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
} catch (NumberFormatException e) {
e.printStackTrace();
Toast.makeText(context, "" + e, Toast.LENGTH_SHORT).show();
}
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("application".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; //MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
} else if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
return getMediaFilePathForN(uri, context);
} else {
return getDataColumn(context, uri, null, null);
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
private static String getPathFromExtSD(String[] pathData) {
String type = pathData[0];
String relativePath = "/" + pathData[1];
String fullPath = "";
if ("primary".equalsIgnoreCase(type)) {
fullPath = getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("SECONDARY_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if ((null == fullPath) || (fullPath.length() == 0)) {
fullPath = System.getenv("EXTERNAL_SDCARD_STORAGE");
return fullPath;
}
/* if (fileExists(fullPath)) {
return fullPath;
}*/
return fullPath;
}
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
InputStream inputStream = null;
FileOutputStream outputStream = null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
}
}
}
return file.getPath();
}
private static String getMediaFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
private static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection,
selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} catch (Exception e) {
// Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
Any help would be appreciated. I am testing on an android R device. Why is it that when selecting the file from a RECENT section in the file browser I am not getting any file path meanwhile selecting the same file in the STORAGE section is returning file path?
I have added only that else part and it's working fine. thank you for helping. referece
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}else {
contentUri = MediaStore.Files.getContentUri("external");
}
I have a problem with this activity file I tried to modify I mean to add a custom font this TextView. I tried many code, it doesn't work for me. hope I will find the solution by this Question.
this my activty code:
private ArrayList<SongInfo> items;
private Context context;
private ArrayList<ViewHolder> listHolder = new ArrayList<ListRingtonesAdapter.ViewHolder>();
private int curPosition = 0;
private RingtonesSharedPreferences pref;
private boolean inRingtones;
static final String TAG = "LOG";
private static final int DEFAULT_RINGTONE = 1;
private static final int ASSIGN_TO_CONTACT = 2;
private static final int DEFAULT_NOTIFICATION = 3;
private static final int DEFAULT_ALARM = 4;
private static final int DELETE_RINGTONE = 5;
public static final String ALARM_PATH = "/media/audio/alarms/";
public static final String ALARM_TYPE = "Alarm";
public static final String NOTIFICATION_PATH = "/media/audio/notifications/";
public static final String NOTIFICATION_TYPE = "Notification";
public static final String RINGTONE_PATH = "/media/audio/ringtones/";
public static final String RINGTONE_TYPE = "Ringtone";
public ListRingtonesAdapter(Context context, int viewResourceId,
ArrayList<SongInfo> objects, boolean inRingtones) {
super(context, viewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.items = objects;
this.pref = new RingtonesSharedPreferences(context);
this.inRingtones = inRingtones;
if(Main.mp.isPlaying()){
Main.mp.stop();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ActionItem defRingtone = new ActionItem(DEFAULT_RINGTONE,
"Default Ringtone", context.getResources().getDrawable(
R.drawable.icon_ringtone));
ActionItem assign = new ActionItem(ASSIGN_TO_CONTACT,
"Contact Ringtone", context.getResources().getDrawable(
R.drawable.icon_contact));
ActionItem defNotifi = new ActionItem(DEFAULT_NOTIFICATION,
"Default Notification", context.getResources().getDrawable(
R.drawable.icon_notify));
ActionItem defAlarm = new ActionItem(DEFAULT_ALARM, "Default Alarm",
context.getResources().getDrawable(R.drawable.icon_alarm));
final QuickAction mQuickAction = new QuickAction(context);
mQuickAction.addActionItem(defRingtone);
mQuickAction.addActionItem(assign);
mQuickAction.addActionItem(defNotifi);
mQuickAction.addActionItem(defAlarm);
// setup the action item click listener
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
switch (actionId) {
case DEFAULT_RINGTONE:
setDefaultRingtone(items.get(curPosition));
Toast.makeText(context,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
break;
case ASSIGN_TO_CONTACT:
Intent intent = new Intent(context,
SelectContactActivity.class);
intent.putExtra("position", curPosition);
context.startActivity(intent);
break;
case DEFAULT_ALARM:
setDefaultAlarm(items.get(curPosition));
Toast.makeText(context,
"Alarm set successfully",
Toast.LENGTH_LONG).show();
break;
case DEFAULT_NOTIFICATION:
setDefaultNotice(items.get(curPosition));
Toast.makeText(context,
"Notification set successfully",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
view.setTag(holder);
} else {
}
final SongInfo item = items.get(position);
if (item != null) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.txtName.setText(item.getName());
if (item.isFavorite()) {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite);
} else {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite_off);
}
if (!item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
} else {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
}
holder.btnPlayPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
for(int i = 0; i < items.size(); i++){
if(items.get(i) != item)
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
if (item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
item.setPlaying(false);
items.get(position).setPlaying(false);
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
} else {
curPosition = position;
playAudio(context, item.getAudioResource());
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
item.setPlaying(true);
items.get(position).setPlaying(true);
}
for (ViewHolder object : listHolder) {
if (object != holder) {
object.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
}
}
});
holder.btnFavorite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (item.isFavorite()) {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite_off);
item.setFavorite(false);
pref.setString(item.getFileName(), false);
if (!inRingtones) {
Intent broadcast = new Intent();
broadcast.setAction("REMOVE_SONG");
context.sendBroadcast(broadcast);
}
} else {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite);
item.setFavorite(true);
pref.setString(item.getFileName(), true);
}
}
});
listHolder.add(holder);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mQuickAction.show(v);
curPosition = position;
}
});
}
return view;
}
private Object getAssets() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int txtsongname) {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
private TextView txtName;
private ImageView btnFavorite;
private ImageView btnPlayPause;
}
private void playAudio(Context context, int id) {
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
Main.mp = MediaPlayer.create(context, id);
Main.mp.setOnCompletionListener(playCompletionListener);
Main.mp.start();
onRingtonePlay.onPlay();
}
private OnCompletionListener playCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
for(int i = 0; i < items.size(); i++){
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause
.setBackgroundResource(R.drawable.icon_play);
}
}
};
private void setRingtone(SongInfo info, boolean ringtone, boolean alarm,
boolean music, boolean notification) {
File dir = null;
String what = null;
if (ringtone) {
what = "Ringtones";
}else if(alarm){
what = "alarms";
}else if(notification){
what = "notifications";
}else{
what = "Ringtones";
}
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} 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
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
String[] projection = new String[] { MediaStore.MediaColumns.DATA,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor c = context.getContentResolver().query(uri,projection,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()+ "\"", null, null);
String strRingtone = null, strAlarm = null, strNotifi = null, strMusic = null;
while (c.moveToNext()) {
strRingtone = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE));
strAlarm = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_ALARM));
strNotifi = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION));
strMusic = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
}
if (ringtone) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (notification) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (alarm) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (music) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
if (ringtone) {
values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtone);
} else if (notification) {
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, notification);
} else if (alarm) {
values.put(MediaStore.Audio.Media.IS_ALARM, alarm);
} else if (music) {
values.put(MediaStore.Audio.Media.IS_MUSIC, music);
}
context.getContentResolver().delete(uri,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath() + "\"", null);
Uri newUri = context.getContentResolver().insert(uri, values);
int type = RingtoneManager.TYPE_ALL;
if (ringtone)
type = RingtoneManager.TYPE_RINGTONE;
if (alarm)
type = RingtoneManager.TYPE_ALARM;
if (notification)
type = RingtoneManager.TYPE_NOTIFICATION;
RingtoneManager.setActualDefaultRingtoneUri(context, type, newUri);
}
private void setDefaultRingtone(SongInfo info) {
File dir = null;
String what = "Ringtones";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} 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
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
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);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
}
private void setDefaultAlarm(SongInfo info) {
File dir = null;
String what = "alarms";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} 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
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_ALARM
};
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_ALARM);
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);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_ALARM, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}
}
private void setDefaultNotice(SongInfo info) {
File dir = null;
String what = "notifications";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} 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
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_NOTIFICATION
};
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_NOTIFICATION);
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);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}
}
private void deleteRingtone(SongInfo info) {
File dir = null;
if (Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
Log.d(TAG, "dir:"+dir.getPath());
File file = new File(dir, info.getFileName());
Log.d(TAG, "file name:"+info.getFileName());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
.getAbsolutePath());
context.getContentResolver().delete(
uri,
MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()
+ "\"", null);
if (file.exists()) {
file.delete();
}
}
OnRingtonePlay onRingtonePlay;
/**
* #param onRingtonePlay the onRingtonePlay to set
*/
public void setOnRingtonePlay(OnRingtonePlay onRingtonePlay) {
this.onRingtonePlay = onRingtonePlay;
}
interface OnRingtonePlay{
public void onPlay();
}
}
i Want to add a font to this "textView"
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
I tried this but it doesnt work for me:
// give the font path
String fontPath = "font/myfont.otf";
TextView txtName = (TextView) findViewById(R.id.txtSongName);
// get the font face
Typeface tf = Typeface.createFromAsset((AssetManager) getAssets(), fontPath);
// Apply the font
txtName.setTypeface(tf);
// holder = (ViewHolder) view.getTag();
and thank you very Much :)
This is how i add a a custom font,check what did you missed
1.Create an assets folder
Add a separate folder/directory for fonts and name it as fonts
3.Add the fonts to that folder
4.Now i can set my font , this is how i do it
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Xcelsion.ttf"); // if you are inside a fragment use -> getActivity().getAssets() .....check your path is correct
TextView myTextView = (TextView)findViewById(R.id.text_view);
myTextView.setTypeface(myTypeface); // set that font to the textview you want
Note : If you are in other Class that accept your Activitie's context use yourContextThatYouGot.getAssets() ,if you are in a fragment use getActivity().getAssets() instead of getAssets()
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;
}
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
Hello sackoverflow I'm trying to develop an application which can backup and restore contacts, my code is as follows
public class MainActivity extends Activity
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
FileOutputStream mFileOutputStream = null;
Button btnRestorects = null;
Button btnBackupCts = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRestorects = (Button) findViewById(R.id.buttonRstCts);
btnBackupCts = (Button) findViewById(R.id.buttonBackCts);
vfile = "contacts.vcf";
final String storage_path = Environment.getExternalStorageDirectory().toString() +"/"+ vfile;
final File f = new File(storage_path);
btnBackupCts.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
if (!f.exists())
f.createNewFile();
mFileOutputStream = new FileOutputStream(storage_path, false);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
getVcardString();
}
});
btnRestorects.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final Intent intent = new Intent();
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString() +"/contacts.vcf");
intent.setDataAndType(Uri.fromFile(file),tmptype);
startActivity(intent);
}
});
}
private void getVcardString()
{
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
try
{
mFileOutputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try
{
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
mFileOutputStream.write(vcardstring.toString().getBytes());
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Permissions in manifest
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So far my code was backing up the contact but only name and contact number, but not retrieving the information like whether the contact is starred or not. Please help me in solving this riddle.
Thanks in advance.
Use this to restore:
final MimeTypeMap mime = MimeTypeMap.getSingleton();
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString()
+ "/contacts.vcf");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(file), "text/x-vcard");
startActivity(i);
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(new File(filePath)), MimeTypeMap.getSingleton().getMimeTypeFromExtension("vcf"));
startActivity(Intent.createChooser(mIntent, "Select App"));