我试图创建一个找到所有mp3歌曲的应用程序,这个代码就是我得到的,但是我无法测试这段代码,因为它崩溃了,没有任何错误,我是什么&#39我做错了吗?
我的班级找到歌曲:
public class SongsManager {
private ArrayList<Song> songsList;
public ArrayList<Song> 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);
} while (cursor.moveToNext());
}
cursor.close();
}
return songsList;
}
}
我的活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SongsManager songsManager = new SongsManager();
ArrayList<Song> songList = songsManager.getMp3Songs(this);
ArrayAdapter<Song> adapterSongList = new ArrayAdapter<Song>(this, android.R.layout.simple_list_item_1, songList);
ListView listView = (ListView) findViewById(R.id.musicList);
listView.setAdapter(adapterSongList);
}
}
我的歌曲课程:
public class Song {
private long id;
private String title;
private String artist;
private String path;
public Song(long songID, String songTitle, String songArtist, String songPath) {
id = songID;
title = songTitle;
artist = songArtist;
path = songPath;
}
public long getID(){
return id;
}
public String getTitle(){
return title;
}
public String getArtist(){
return artist;
}
public String getPath(){
return path;
}
public void setTitle(String title_param){
title = title_param;
}
public void setArtist(String artist_param){
title = artist_param;
}
public void setPath(String path_param){
path = path_param;
}
public String toString(){
return getTitle();
}
}
答案 0 :(得分:0)
您使用了错误的语法。 “选择”不正确,因为这是排序顺序。
例如:
private final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
public Cursor getAllTracks(Context context) {
// gets all tracks
ContentResolver cr = context.getContentResolver();
final String[] columns = {track_id, track_no, artist, track_name,
album, duration, path, year, composer};
return cr.query(uri, columns, null, null, null);
}
来自文档:
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
查询给定的URI,在结果集上返回一个Cursor。