Get content uri of an audio file from its absolute path - android

I have gone through a lot of stackoverflow questions but I couldn't find an answer to this. There is an answer for Image files but that doesn't work in my case.
So I have the absolute path of the file using file.getAbsolutePath(). But I need to convert it to contentUri so that below query works fine.
Cursor tempCursor = context.getContentResolver().query(uri,
proj, null, null, null);
It is not working. I tried Uri.parse(contentUri) but that doesn't give the content uri I guess. Please help me, I am stuck since a long time. Thanks !!

You do not use the get.absolute etc. Simply query the Medfiastore.Audio etc and bring back _id and _DATA. _id is the song id and _DATA has the full path and track
below a piece of code which you could use. Just feed it the track name
public String getThisTrackId(Context context, String trackName) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String path = MediaStore.Audio.Media.DATA;
final String[] columns = { _id };
final String[] trackname = { "%"+ trackName +"%" };
String where = path + " LIKE ?";
String strtrack_id = null;
Cursor crs =cr.query(uri, columns, where, trackname, null);
if(crs!= null && crs.moveToFirst()){
strtrack_id = crs.getString(crs.getColumnIndexOrThrow(_id));
crs.close();
}
return strtrack_id;
}

Related

I want to get a cursor to one file only. But how?

I am new to android. I want get cursor to one file only. But how? I tried this but doesn't work and gives error.
private void getallaudioFromMySpecialFolder() {
String[] star = { "*" };
String Dir_recordedAudios= Environment.getExternalStorageDirectory()+File.separator+"My Audios"+File.separator;
File Directory=new File(Dir_recordedAudios);
Uri u=Uri.fromFile(Directory);
Uri uri = Uri.parse(u.toString());
Cursor musiccursor = managedQuery(uri, star,null, null, null);
if (musiccursor!= null) {
if (musiccursor.moveToFirst()) {
do {
String duration = musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String str_duration=CalTotalTime(Integer.valueOf(duration));
String path= musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Log.d("************", "**************");
Log.d("path",path);
Log.d("totalTime", str_duration);
} while (musiccursor.moveToNext());
}
musiccursor.close();
}
}
I finally Find my question solving . If we want cursor to a special file,first in Projection array determine aour fileds for projection. And we must define aur file which want fetching its info.
We use of a statement with "LIKE" word for selection. Code is here. Too,I learned that using from CursorLoader is better.because managedQuery method is deprecated.
Code is here:
String name="";
String duration="";
String path="";
Log.d("Loading file: " + filepath,"");
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri audiosUri = MediaStore.Audio.Media.getContentUri("external");
Log.d("audiosUri = " + audiosUri.toString(),"");
String[] projection = {MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.DURATION};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = managedQuery(audiosUri, projection, MediaStore.Audio.Media.DATA + " LIKE ?", new String[] { filepath }, null);
cursor.moveToFirst();
path =cursor.getString( cursor.getColumnIndex(projection[0]));
name=cursor.getString( cursor.getColumnIndex(projection[1]));
int iduration = cursor.getColumnIndex(projection[2]);
duration=CalTotalTime(Integer.valueOf(iduration));
Log.d("pathhhhhhhhhhhhhhhhhh", path);
Log.d("nameeeeeeeeeeeeeeeeeeeeeee", name);
Log.d("duration", duration);
cursor.close();
And this is a formal of CursorLoader .May be helps you.
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(proj[0]);
cursor.moveToFirst();
return cursor.getString(column_index);
}

How to actually search for a song in a mediastore cursor using a string

I have set up the cursor but I am still struggling with actually searching it. How do I search for the track name? How do I get its ID so I can pass it to mediaplayer? I have tried different things but didn't succeed.
Basically, I want to know how to search the mediastore for a certain string (string songToPlay in this case), get the results, get the ID of the best match and pass it to my mediaplayer service to play it in the background. The only thing I am asking you is how to get the ID though.
This is the code I am using:
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] songToPlay = value.split("play song");
String[] searchWords = songToPlay[1].split(" ");
String [] keywords = null;
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
String selection = where.toString();
String[] projection = {
BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
Cursor cursor = this.managedQuery(uri, projection, selection, keywords, MediaStore.Audio.Media.TITLE);
if (cursor.moveToFirst()) {
do{
test.setText(cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
}while(cursor.moveToNext());
}
I'm very confused and most of this code is from the internet. I have been trying to do this for 2 days now, that's why I'm asking here. I've done hours of trying by myself.
edit: Current code. How am I supposed to find the location - music ID or whatever I need to play that song from the cursor?
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String songToPlay = value.replaceAll("play song", "").trim();
int music_column_index;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
#SuppressWarnings("deprecation")
Cursor cursor = this.managedQuery(uri,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
This will search the MediaStore for all songs with title equal to the value of your songToPlay string.
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
You can then of course query the cursor to get the ID (and any other column) of any results.
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
// Whatever else you need
}
However this will require an exact match, you may like to use the LIKE operator for a more fuzzy match.

How to get imagepath from thumbnail path of a image?

I am trying to get imagepath based on thumbail path , i have already tried solution from
android-getting-path-to-image-from-thumbnail, but it is based on gridview position, i am only retrieving specific images. Also i found one sample code from SO, the code is
private String getImagePathFromThumbPath(String thumbPath)
{
String imgPath=null;
// String[] projection = new String[] {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.IMAGE_ID};
String[] imagesDataPath={ MediaStore.Images.Media.DATA ,MediaStore.Images.Media._ID};
//mResolver.query() requires android API 16
Cursor thumbnails = mResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imagesDataPath,MediaStore.Images.Thumbnails.DATA+"=?",new String[]{thumbPath}, null, null);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor imageCursor = mResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, MediaStore.Images.Media._ID + "=?", new String[] {thumbId}, null);
if (imageCursor != null && imageCursor.moveToFirst()) {
// Your file-path will be here
imgPath= imageCursor.getString(imageCursor.getColumnIndex(filePathColumn[0]));
}
return imgPath;
}
The above method is bit modified to suit my needs and it returns nothing on Toasting, please tell how to retrieve imagepath using thumbnail path?
After a long time and relentless try, the solution is here
1. You need to find the image id which is image unique id from images table in thumbnail table, query to thumbnail provider (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI) if you do not understand it, refer here , specifically IMAGE_ID,
Step 1 is to get retrievedImageId.
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
2. Now using the retrievedImageId get the image path, by again querying the content provider, only this time query the Images media provider (MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
String getImagePathFromThumbPath(String thumbPath)
{
String imagePath = null;
if(thumbPath != null )
{
String[] columns_to_return = {MediaStore.Images.Thumbnails.IMAGE_ID};
String where = MediaStore.Images.Thumbnails.DATA+" LIKE ?";
long retrievedImageId = -1;
String valuesAre[] = {"%"+thumbPath};
Cursor cursor = getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns_to_return, where, valuesAre, null);
if(cursor != null)
{
int imageIdInImages = cursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
for (cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext())
{
//STEP 1 to retrieve image ID
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
}
if(retrievedImageId != -1)
{
// STEP 2 Now
Log.i(TAG, "imageId-" + retrievedImageId);
String[] columnsReturn = {MediaStore.Images.Media.DATA};
String whereimageId = MediaStore.Images.Media._ID+" LIKE ?";
String valuesIs[] = {"%" + retrievedImageId};
Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columnsReturn, whereimageId, valuesIs, null);
int rawDataPath= mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
for (mCursor.moveToFirst();!mCursor.isAfterLast(); mCursor.moveToNext())
{
imagePath = mCursor.getString(rawDataPath);
}
}
}
}
return imagePath;
}
If you still have doubt or error/exception, leave comment!

LOOKUP_KEY and CONTENT_LOOKUP_URI

I have the following code to get details of a contact.
"data": is the Uri I get back after selecting the contact.
I need to be sure that I will get to the right contact in the future so what should I be saving for future use? Is it "lookupUri" or "lookupKey"?
Cursor c = activity.managedQuery(data, null, null, null, null);
c.moveToFirst();
String lookupKey = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY ));
c.close();
// Next use that key to access the details of the contact in order to get the name and the photo
// Also, save it for future use.
// It will be used when we fetch the details from the database since the photo itself is not saved.
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI,lookupKey);
Uri uri = ContactsContract.Contacts.lookupContact(activity.getContentResolver(), deviceDetails.lookupUri);
LookupKey is the unique identifier that you want to store.
FYI; There is a bug in 2.1 where un-synced contacts LookupKey changes when the name is changed.
This works. My example looks up the name; add or remove the fields you want in the projection.
private String getContactNameFromAndroidKey (String key)
{
// Run query
Uri uri = Uri.parse (ContactsContract.Contacts.CONTENT_LOOKUP_URI + "/" + key);
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
Cursor cursor = context.getContentResolver().query (
uri,
projection,
null,
null,
null);
if (!cursor.moveToNext()) // move to first (and only) row.
throw new IllegalStateException ("contact no longer exists for key");
String name = cursor.getString(1);
cursor.close();
return name;
}

How to get track Uri from ContentResolver query?

i am traversing in the phone's memory with the following code.
ContentResolver contentResolver = getContentResolver();
String[] columns = {
MediaColumns._ID,
MediaColumns.TITLE,
AudioColumns.DURATION,
};
final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns, where, null, null);
while(cursor.moveToNext()) {
String urp = cursor.getString(cursor.getColumnIndex(MediaColumns._ID));
String title = cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE));
Long duration = cursor.getLong(cursor.getColumnIndex(AudioColumns.DURATION));
}
so now my question is, how to get the uri of the cursor items traveresed, like
for first while run i have stored id,title,duration etc metadata and i would also like to
store that tracks URI, also i would like to convert that URI from content// scheme to file scheme.
Any help will be greatful
thankyou
String.valueOf(cur.getColumnIndex(android.provider.MediaStore.MediaColumns.DATA)));
http://android-er.blogspot.fr/2011/04/convert-uri-to-real-path-format.html

Categories

Resources