2017-03-05 52 views
0

我試圖找到所有的MP3文件,但一個也不知道,我發現這個代碼,唯一的問題是getActivity()沒有宣佈,我不知道如何修復,請幫助我。如果有更好的方法來做到這一點,我接受消化。找到所有的MP3文件存儲在Android

這裏是我的類:

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(); 
     } 
    } 
} 

回答

1

爲方法(getMp3Songs)設定的參數作爲上下文:

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(); 
    } 
} 

}

0

創建構造函數,並把那裏語境。然後調用上下文而不是getActivity();

public class SongsManager { 

private Context context; 

public SongsManager(Context context){ 
this.context = context; 
} 
} 
相關問題