码迷,mamicode.com
首页 > 移动开发 > 详细

Android Cursor空指针的问题

时间:2015-01-26 10:01:57      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

最近几天无聊自己动手写个音乐播放器,用到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空指针的问题

标签:

原文地址:http://www.cnblogs.com/zhujiabin/p/4249411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!