存储并遍历查询结果

时间:2017-12-18 20:18:24

标签: java android cursor mediastore

我有一个音乐应用程序,它一直工作到现在。

我的SD卡里面有超过1000首歌曲。哪个显示在recycler view

在我不需要特定歌曲的专辑封面之前,但现在我想让我的应用程序更好一点,我找到了一种方法来获得每首歌曲的专辑封面。

我尝试了什么:

        ContentResolver contentResolver=getContentResolver();
        Uri musicUri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor=contentResolver.query(musicUri,null,MediaStore.Audio.Media.IS_MUSIC + "=1",null,null);

        if(cursor!=null && cursor.moveToFirst()){
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int imgSrcColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);

            do {
                long thisID = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                String thisArtist = cursor.getString(artistColumn);
                long thisImg = cursor.getLong(imgSrcColumn);
                Cursor cursorx = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                        new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
                        MediaStore.Audio.Albums._ID+ "=?",
                        new String[] {String.valueOf(thisImg)},
                        null);

                try {
                    if (cursorx.moveToFirst()) {
                        String path = cursorx.getString(cursorx.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
                        this.songs.add(new Song(thisID, thisTitle, thisImg,thisArtist,path));
                    }
                    cursorx.close();
                }
                catch (NullPointerException e)
                {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());

现在这个工作正常,我得到了预期的结果,但我的应用程序加载歌曲,即歌曲列表需要花费太多时间。

我认为其他音乐播放器也是如此,但加载时间却少了。就像我说play music一样,最多需要2-3秒。我的大约需要10-12秒,甚至更多。

也许是因为我每次需要专辑封面时都在查询SD卡。

Cursor cursorx = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                    new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
                    MediaStore.Audio.Albums._ID+ "=?",
                    new String[] {String.valueOf(thisImg)},
                    null);

任何存储结果然后循环的方法?就像我们在php or any other language中所做的那样,从数据库中获取结果一次,然后循环遍历它。而不是每次都打电话。

任何更好的方法也值得赞赏!

P.s:在使用此东西之前,app的加载时间最长为1秒

0 个答案:

没有答案
相关问题