Slow loading times in MusicPlayerApp - java

Hey so I just made an android app which basically fetches all the mp3/wav files from your phone and then shows them it to you. Which you can then play them. But I am experiencing slow load times. My phone has like 10 mp3 and its a 6GB RAM phone. But it takes like 1 minute to load all those files. I am using the built in MediaPlayer Class. Any tips?

Use this code.
for reference link
public void getMp3Songs() {
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
songsList.clear();
Cursor cursor = managedQuery(allsongsuri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
songsList.add(fullpath);
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
Toast.makeText(context, ""+songsList.size(), Toast.LENGTH_SHORT).show();
}

Related

Adding songs to a playlist in Android Q (API29) and above throws a SecurityException

Because of the Android Privacy Changes in Android Q (API29) it's not possible to add songs to a Playlist and it throws this error message when adding a track.
java.lang.SecurityException: com.mp3player.mp3player has no access to content://media/external_primary/audio/media/117
I know that we can this catch this as a RecoverableSecurityException and grant permission for each file individually.
But this is really a hassle and i'm wondering if there is another way.
I already found a post from User #Theo with the same exact problem but without any answers.
Code for adding songs to a playlist
public void addToPlayList(Context c, long songID, long playListID, String playlistName) {
Uri playListUri = MediaStore.Audio.Playlists.Members.getContentUri("external", playListID);
String[] columns = {
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Playlists.Members.PLAY_ORDER,
};
ContentResolver resolver = c.getContentResolver();
Cursor cursor = resolver.query(playListUri, columns, null, null, null);
int playOrder = 0;
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
playOrder = cursor.getInt(0) + 1;
}
cursor.close();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songID);
contentValues.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, playOrder);
resolver.insert(playListUri, contentValues);
resolver.notifyChange(Uri.parse("content://media"), null);
}
EDIT
Looks like the thrown Exception is not an instance of RecoverableSecurityException so how do we get access to that content?
you can use playListUri.getpath() and solve it.

I want to display the total number of messages in my device

Is there a way of determining the number of total messages in our device.
I've tried the following for finding the number of calls:
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
count= c.getCount();
Log.i("TAG",Integer.toString(count));
But I'm not able to view any number when i tried this similar to messages in my logcat.
Try this code to get all Messages
public List<String> getSMS(){
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
while (cur != null && cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
if (cur != null) {
cur.close();
}
return sms;
}
Just Call the method and you will receive an ArrayList of all messages
Get List of Messages in Inbox Like Below:
First Add Permission in Manifest.xml to read sms:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
public ArrayList<String> fetchInbox()
{
ArrayList<String> sms = new ArrayList();
//Read Draft message only by "content://sms/draft"
//Read Sent message only by "content://sms/sent"
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(body);
}
return sms;
}
And You can get SMS count by sms.size();

MediaStore External Content URI is fetching data from SDCARD

I am using MediaStore and Cursor to fetch audio files from a specified folder. What I want is that, it should fetch the list of songs from the phone's internal storage but it is fetching from SDCARD. Although I have tried using INTERNAL_CONTENT_URI but it is not getting anything at all. Kindly have a look, what's wrong in it. Any help will be appreciated.
String AudioFilePath = "%" +"/nexcox/voicerecorder/audio/" +"%";
Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection= MediaStore.Audio.Media.DATA +" LIKE ? ";
Cursor cursor=context.getContentResolver().query(uri,null,selection,
new String[]{AudioFilePath},
null);
if (cursor!=null){
if (cursor.moveToFirst()){
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String sourceLocation = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
AudioInfo audioInfo=new AudioInfo(name,duration,sourceLocation);
audioInfos.add(audioInfo);
}while (cursor.moveToNext());
}
cursor.close();
audioAdapter=new AudioAdapter(context,audioInfos);
recyclerView.setAdapter(audioAdapter);
}
for example
String fullpath = trackcursor.getString(trackcursor.getColumnIndex(MediaStore.Audio.Media.DATA))
if(fullpath.contains(Environment.getExternalStorageDirectory(){
// you have the internal sdcard
}
In your code:
if (cursor!=null){
if (cursor.moveToFirst()){
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String sourceLocation = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
if(sourceLocation.contains(Environment.getExternalStorageDirectory(){
// you have the internal sdcard
AudioInfo audioInfo=new AudioInfo(name,duration,sourceLocation);
audioInfos.add(audioInfo);
}
}while (cursor.moveToNext());
}
cursor.close();
audioAdapter=new AudioAdapter(context,audioInfos);
recyclerView.setAdapter(audioAdapter);
}
I use the same approach as your example. Works fine.
public Cursor getMediastoreTrackDetails(Context context, String trackName) {
if(context!=null) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String path = MediaStore.Audio.Media.DATA;
final String album = MediaStore.Audio.Media.ALBUM;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String[] columns = {_id, path,album, album_id};
final String[] trackname = {"%" + trackName + "%"};
String where = path + " LIKE ?";
return cr.query(uri, columns, where, trackname, null);
}else{
return null;
}
}

Cursor doesn't refresh until I restart device in android

I'm developing camera app now and can record videos in app folder successfully.
Btw when I read videos from app folder with Cursor, it doesn't refresh cursor. (It means when I record video with app and whenever I want to view videos via app, it shows old videos. even when I close app and re-open app it shows old videos. )
Here's source code.
public static List<MyVideo> getAppVideos(Context context) {
final String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.DATE_TAKEN, MediaStore.Video.Media.DURATION};
final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
final String[] selectionArgs = { APP_VIDEO_BUCKET_ID };
final Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
null);
ArrayList<MyVideo> result = new ArrayList<MyVideo>(cursor.getCount());
if (cursor.moveToFirst()) {
final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
final int dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_TAKEN);
final int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
do {
final String data = cursor.getString(dataColumn);
final String createdDate = cursor.getString(dateColumn);
final String durationTime = cursor.getString(durationColumn);
result.add(new MyVideo(data, DateUtils.convertToSeconds(durationTime), "^ " + DateUtils.getDateFromMilliSeconds(Long.parseLong(createdDate), "MMM dd, yyyy")));
} while (cursor.moveToNext());
}
cursor.close();
return result;
}
Could anyone please suggest solution?
If CursorDemo extends CursorAdapter, then you have to use adapter.swapCursor(cursor_update);
That should swap the old cursor out for the new one and reload the data. With swapCursor,since the old cursor is not closed.

Android: I have a list of contact names, how to get their corresponding emails and pohone numbers?

I have an activity that has a listview which displays all contacts with multi-selection enabled. I have also a filter to filter the display result.
After struggling with this problem for 3 days, I finally could produce a list of all display names selected by the user.
My question now is how to get the corresponding email and phone number for each display name in my list?
Update:
I found a solution..
public String getNumber(String name,Context context){
String number="";
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = context.getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String Name = people.getString(indexName);
String Number = people.getString(indexNumber);
if(Name.equalsIgnoreCase(name)){return Number.replace("-", "");}
// Do work...
} while (people.moveToNext());
if(!number.equalsIgnoreCase("")){return number.replace("-", "");}
else return number;
}
public String getEmail(String name,Context context){
String email="";
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA};
Cursor people = context.getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
people.moveToFirst();
do {
String Name = people.getString(indexName);
String mail = people.getString(indexNumber);
if(Name.equalsIgnoreCase(name)){return mail;}
// Do work...
} while (people.moveToNext());
if(!email.equalsIgnoreCase("")){return email;}
else return email;
}
Got it from there:
Android get contact number using name

Categories

Resources