Android開發教程:關於Cursor空指針的問題
最近自己動手寫個音樂播放器,用到Cursor來取得數據庫中音樂文件的信息,但是當用到Cursor的時候總是報空指針錯誤,後來發現是模擬器上沒有音樂文件,使用Cursor的時候 ,若Cursor中沒有結果,則Cursor的對象則為空,所以在使用Cursor的時候最好先判斷Cursor對象是否為空且其結果是否大於等於1,
以下是最開始的代碼:
private void getSongMessage(){
String TITLE = MediaStore.Audio.Media.TITLE;
String DATA = MediaStore.Audio.Media.DATA;
String ALBUM = MediaStore.Audio.Media.ALBUM;
String ARTIST = MediaStore.Audio.Media.ARTIST;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cs = cr.query(uri, null, null, null, null);
while (cs.moveToNext()) {
String title = cs.getString(cs.getColumnIndex(TITLE));
String data = cs.getString(cs.getColumnIndex(DATA));
String album = cs.getString(cs.getColumnIndex(ALBUM));
String artist = cs.getString(cs.getColumnIndex(ARTIST));
MusicData.title.add(title);
MusicData.data.add(data);
MusicData.album.add(album);
MusicData.artist.add(artist);
}
}
以下是修改後的代碼:
private void getSongMessage(){
String TITLE = MediaStore.Audio.Media.TITLE;
String DATA = MediaStore.Audio.Media.DATA;
String ALBUM = MediaStore.Audio.Media.ALBUM;
String ARTIST = MediaStore.Audio.Media.ARTIST;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cs = cr.query(uri, null, null, null, null);
if(cs != null && cs.getCount() >= 1){
while (cs.moveToNext()) {
String title = cs.getString(cs.getColumnIndex(TITLE));
String data = cs.getString(cs.getColumnIndex(DATA));
String album = cs.getString(cs.getColumnIndex(ALBUM));
String artist = cs.getString(cs.getColumnIndex(ARTIST));
MusicData.title.add(title);
MusicData.data.add(data);
MusicData.album.add(album);
MusicData.artist.add(artist);
}
}else{
Toast.makeText(this, "No Data", Toast.LENGTH_LONG).show();
}
}
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11