2017-03-05 5 views
0

私はすべてのmp3ファイルを見つけようとしていますが、私はこのコードを見つけましたが、唯一の問題はgetActivity()は宣言されていませんでした修正するには、私を助けてください。これを行うより良い方法があれば、私は摂取を受け入れます。android内のすべてのmp3ファイルを見つける

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; 
} 
} 
関連する問題