我试图找到所有的mp3文件但是我不知道并且我发现了这个代码,唯一的问题是 getActivity()没有声明,我不知道怎么修复,请帮我。如果有更好的方法,我接受消化。
这是我的班级:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs() {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = getActivity().getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
答案 0 :(得分:1)
将Method(getMp3Songs)的参数设置为Context:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs(Context ctx) {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = ctx.getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
答案 1 :(得分:0)
创建构造函数并将其放在Context中。然后调用context而不是getActivity();
public class SongsManager {
private Context context;
public SongsManager(Context context){
this.context = context;
}
}