Tuesday, February 28, 2012

Get info of a specified item in MediaStore.Audio.Media

Modify from last exercise "List audio media in MediaStore.Audio.Media", override onListItemClick() to display info of the clicked item.
Get info of a specified item in MediaStore.Audio.Media
package com.exercise.AndroidListMedia;

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Video.Media;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class AndroidListMediaActivity extends ListActivity {

SimpleCursorAdapter adapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = {
MediaStore.MediaColumns.TITLE};
int[] to = {
android.R.id.text1};

Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Audio.Media.TITLE);

adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, from, to);
setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);

String _id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));

String info = "_ID: " + _id + "\n"
+ "TITLE: " + title + "\n"
+ "ARTIST: " + artist + "\n"
+ "ALBUM: " + album + "\n"
+ "DURATION: " + duration/1000 + "s";

Toast.makeText(this, info, Toast.LENGTH_LONG).show();
}


}


Download the files.

Next:
- Retrieve playable Uri from MediaStore, pointed by cursor.

No comments: