首页 > 代码库 > Android Cursor空指针的问题

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 Cursor空指针的问题