我希望在我的应用上有一个ListView
,它会填充我外部存储设备上的所有mp3文件。
这是onCreate方法中的代码。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mListView = (ListView) findViewById(R.id.listView1);
List<DoubleString> mList = new ArrayList<DoubleString>();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE;
ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = resolver.query(uri, null, selection, null, sortOrder);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int artist = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
long mId = cursor.getLong(id);
String mTitle = cursor.getString(title);
String mArtist = cursor.getString(artist);
String mData = cursor.getString(data);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(mData);
String mimeType = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
if (mimeType == "audio/mpeg") {
mList.add(new DoubleString(mId, mTitle, mArtist, mData));
}
}
while (cursor.moveToNext());
}
final DoubleStringAdapter adapter = new DoubleStringAdapter(this, mList);
mListView.setAdapter(adapter);
但ListView
返回null,即不会在ListView
上填充任何内容。
所以我的问题是:
MediaStore
&amp; MediaMetadataRetriever
?答案 0 :(得分:0)
您可以通过以下使用MediaStore的代码来执行此操作。请添加外部存储权限。 机器人:名称= “android.permission.WRITE_EXTERNAL_STORAGE”
代码是 -
public ArrayList<HashMap<String, String>> getSDCardAudioFiles() {
// if you want file path and additional details
ArrayList<HashMap<String, String>> audioFilesDetailList = new ArrayList<HashMap<String, String>>();
// if you want only file path
ArrayList<String> audioFilePath =new ArrayList<String>();
// if you want only file name
ArrayList<String> audioFileName =new ArrayList<String>();
Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA }, null, null, null);
int count = mCursor.getCount();
HashMap<String, String> audioFileMap;
while (mCursor.moveToNext()) {
audioFileMap = new HashMap<String, String>();
audioFileMap.put("FileName",mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
audioFileMap.put("FilePath", mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
if(audioFileMap.get("FileName").endsWith(".mp3")){
audioFilesDetailList.add(audioFileMap);
// if you want only file path
audioFilePath.add(audioFileMap.get("FilePath"));
// if you want only file name
audioFileName.add(audioFileMap.get("FileName"));
}
}
mCursor.close();
//return the arraylist whichever u needed
return audioFilesDetailList;
}