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
Related
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;
}
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);
}
my app creates new contacts with ContentProviderOperation. The problem is, I need a reference to the new contact because I need some information of it to display it in a listview and go with intent into the contact app to the contact.
The best thing would be the ID, but I´ve read that it might change during operations on the database, which won´t be helpful to me.
Now I thought, the Uri might be the best thing, because I could later retrieve the contactID or lookup key.
How do I get the Uri directly after calling applyBatch() ?
EDIT:
Here is a solution, but not really a good one.
He is putting a randomly generated token into each contact, then he makes a new query with it.
I want neither put some extra data into the contacts, nor starting a second query. But if there is no other possibility I´ll do it that way.
simply call
private String retrieveContactId(String phoneNo) {
try {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
String[] projection = new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
ContentResolver cr = getApplicationContext().getApplicationContext().getContentResolver();
String contactId = null;
if (cr != null) {
Cursor resultCur = cr.query(uri, projection, selection, selectionArgs, sortOrder);
if (resultCur != null) {
while (resultCur.moveToNext()) {
contactId = resultCur.getString(resultCur.getColumnIndex(ContactsContract.PhoneLookup._ID));
Log.e("Info Incoming", "Contact Id : " + contactId);
return contactId;
}
resultCur.close();
}
}
} catch (Exception sfg) {
Log.e("Error", "Error in loadContactRecord : " + sfg.toString());
}
return null;
}
and for the uri
Uri contactUri = Contacts.getLookupUri(
Integer.valueOf(rawContactId), clookup);
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.
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;
}