MediaStore External Content URI is fetching data from SDCARD - java

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

Related

Slow loading times in MusicPlayerApp

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

Mediastore albums and media columns

Too retrieve the album id i use:
String SONG_ALBUMID = MediaStore.Audio.Albums.ALBUM_ID;
But what is the difference between MediaStore.Audio.Albums.ALBUM_ID and MediaStore.Audio.Media.ALBUM_ID
Thanks,
MediaStore.Audio.Albums.ALBUM_ID is the album id from the albums table and
MediaStore.Audio.Media.ALBUM_ID will be the "foreign key" album_id in the files table.In general relational database design is such that when accessing the files table, all we need is the abum_id to access the albums table and retrieve all relevant albums info such as album_title.The table files in the android database holds lots of details
eg
_id INTEGER
_data TEXT
_size INTEGER
format INTEGER
parent INTEGER
date_added INTEGER
date_modified INTEGER
mime_type TEXT
title TEXT
description TEXT
_display_name TEXT
picasa_id TEXT
orientation INTEGER
latitude DOUBLE
longitude DOUBLE
datetaken INTEGER
mini_thumb_magic INTEGER
bucket_id TEXT
bucket_display_name TEXT
isprivate INTEGER
title_key TEXT
artist_id INTEGER
album_id INTEGER
composer TEXT
track INTEGER
year INTEGER
is_ringtone INTEGER
is_music INTEGER
is_alarm INTEGER
is_notification INTEGER
is_podcast INTEGER
album_artist TEXT
duration INTEGER
bookmark INTEGER
artist TEXT
album TEXT
resolution TEXT
tags TEXT
category TEXT
language TEXT
mini_thumb_data TEXT
name TEXT
media_type INTEGER
old_id INTEGER
storage_id INTEGER
is_drm INTEGER
width INTEGER
height INTEGER
Here are 2 approaches:
(include the requested columns in your resolver.query)
public String getalbum_id(Cursor pcursor) {
int album_col = pcursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
String album_id = pcursor.getString(album_col);
if (album_id.length() > 0) {
return album_id;
} else {
return "";
}
}
public String getAlbumIdfromPath(Context context, String datapath) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String path = MediaStore.Audio.Media.DATA;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String[] columns = {_id, album_id};
final String[] trackpath = {"%" + datapath + "%"};
String where = path + " LIKE ?";
String stralbum_id = null;
Cursor crs = cr.query(uri, columns, where, trackpath, null);
if (crs != null && crs.moveToFirst()) {
stralbum_id = crs.getString(crs.getColumnIndexOrThrow(album_id));
crs.close();
}
return stralbum_id;
}
now to display, I have posted previously but I use the Gilde library. It does all the hard work.
// loading album cover using Glide library
String artist_id = (c.getString(c
.getColumnIndex(MediaStore.Audio.Artists._ID)));
Cursor albs = albums.getArtistsAlbumcursor(mContext, artist_id);
String stralbumId=null;
if(albs!=null && albs.moveToFirst()){
stralbumId= albs.getString(albs.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
Uri ImageUrl = plist.getAlbumUri(mContext, stralbumId);
if (ImageUrl != null) {
Glide.with(mContext)
.asBitmap()
.load(ImageUrl)
.into(image);
}
}
where getAlbumuri is:
public Uri getAlbumUri(Context mContext,String album_id){
if(mContext!=null) {
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri imageUri = Uri.withAppendedPath(sArtworkUri, String.valueOf(album_id));
return imageUri;
}
return null;
}
Include the following in your module build.gradle
implementation 'com.github.bumptech.glide:glide:4.5.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
private final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

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

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