获取相册名称为Android的专辑封面

时间:2012-12-03 06:43:54

标签: android android-mediaplayer mediastore android-contentresolver albumart

我想在listview中显示带有专辑名称的专辑封面。但我没有得到显示专辑封面的方式。我试过cover art on android

这是我的代码:

Cursor cursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, null, null, null);
          if (cursor == null) 
          {
              //Query Failed , Handle error.
          }
          else if (!cursor.moveToFirst()) 
          {
             //No media on the device.
          }
          else
          {
              int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ART);
              int id = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ID); //here value i m getting -1 .

              for(int i=0;i<cursor.getCount();i++)
              {
                  if(id<0)
                  {
                        Long album =Long.parseLong(cursor.getString(id)); 
                        String coverPath = cursor.getString(titleColumn);

                        Context context = null;
                        ContentResolver res = context.getContentResolver();
                        Uri uri = ContentUris.withAppendedId(sArtworkUri, album);
                        if (uri != null)
                        {
                            InputStream in = null;
                            try
                            {
                                in = res.openInputStream(uri);
                                Bitmap b = BitmapFactory.decodeStream(in, null, sBitmapOptions);
                                ImageView coverAlbum=(ImageView)findViewById(R.id.thumbnail);
                                coverAlbum.setImageBitmap(b);

                            } catch (FileNotFoundException ex)
                            {

                            }

                        }

                  }
                         //code to insert in listview
                  cursor.moveToNext();
               }
           }
           cursor.close();
}

但我得到的是album_id -1。所以我没有获得专辑的album_id,但我在我的SD卡上有专辑歌曲。并且sdcard有像 albumthums 这样的文件夹,其中包含一些文件。所以,请给我解决方案,以获得专辑名称和艺术。 提前完成。


这是我的错误日志:

12-03 15:19:22.051: WARN/System.err(32334): java.lang.NullPointerException
12-03 15:19:22.060: WARN/System.err(32334):     at com.mnp.AlbumList.onCreate(AlbumList.java:59)
12-03 15:19:22.120: WARN/System.err(32334):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-03 15:19:22.130: WARN/System.err(32334):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
12-03 15:19:22.140: WARN/System.err(32334):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-03 15:19:22.161: WARN/System.err(32334):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-03 15:19:22.171: WARN/System.err(32334):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-03 15:19:22.180: WARN/System.err(32334):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-03 15:19:22.201: WARN/System.err(32334):     at android.os.Looper.loop(Looper.java:123)
12-03 15:19:22.210: WARN/System.err(32334):     at android.app.ActivityThread.main(ActivityThread.java:4363)
12-03 15:19:22.220: WARN/System.err(32334):     at java.lang.reflect.Method.invokeNative(Native Method)
12-03 15:19:22.240: WARN/System.err(32334):     at java.lang.reflect.Method.invoke(Method.java:521)
12-03 15:19:22.250: WARN/System.err(32334):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-03 15:19:22.260: WARN/System.err(32334):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-03 15:19:22.270: WARN/System.err(32334):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:23)

使用以下代码获取包含歌曲信息的专辑封面。您可以稍微更改以仅显示专辑名称而不是歌曲列表。

 public class BrowseAudioActivity extends Activity implements
            AppConstants {
        private Context context;
        private ArrayList<AudioListModel> audioArrayList = new ArrayList<AudioListModel>();
        private AudioListAdapter audioListAdapter;
        private ListView audioListView;



/** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            setContentView(R.layout.audio_list);
            UtilityClass.addActivityToStack(this);
            context = this;
            audioListView = (ListView) findViewById(R.id.list_audio);

            new GetAudioListAsynkTask(context).execute((Void) null);



        }

        private void initLayout() {
            final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            final String[] cursor_cols = { MediaStore.Audio.Media._ID,
                    MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
                    MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
                    MediaStore.Audio.Media.ALBUM_ID,
                    MediaStore.Audio.Media.DURATION };
            final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
            final Cursor cursor = context.getContentResolver().query(uri,
                    cursor_cols, where, null, null);

            while (cursor.moveToNext()) {
                String artist = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String track = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String data = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                Long albumId = cursor.getLong(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));

                int duration = cursor.getInt(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                Uri sArtworkUri = Uri
                        .parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);

                Logger.debug(albumArtUri.toString());
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(
                            context.getContentResolver(), albumArtUri);
                    bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);

                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                    bitmap = BitmapFactory.decodeResource(context.getResources(),
                            R.drawable.audio_file);
                } catch (IOException e) {

                    e.printStackTrace();
                }

                AudioListModel audioListModel = new AudioListModel();
                audioListModel.setArtist(artist);
                audioListModel.setBitmap(bitmap);
                audioListModel.setAlbum(album);
                audioListModel.setTrack(track);
                audioListModel.setData(data);
                audioListModel.setAlbumId(albumId);
                audioListModel.setDuration(duration);
                audioListModel.setAlbumArtUri(albumArtUri);

                audioArrayList.add(audioListModel);

            }

        }

        public String getRealPathFromURI(Uri contentUri) {
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(contentUri, proj,
                    null, null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

        private class GetAudioListAsynkTask extends AsyncTask<Void, Void, Boolean> {

            private Context context;
            private CustomProgressDialog progressDialog;

            public GetAudioListAsynkTask(Context context) {

                this.context = context;
            }

            @Override
            protected void onPreExecute() {
                progressDialog = new CustomProgressDialog(context,
                        AUDIO_LOADING_HEADING, AUDIO_LOADING_MSG);
                progressDialog.setCancelable(false);
                progressDialog.show();
                super.onPreExecute();

            }

            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    initLayout();

                    return true;
                } catch (Exception e) {
                    return false;

                }

            }

            @Override
            protected void onPostExecute(Boolean result) {
                progressDialog.dismiss();

                audioListAdapter = new AudioListAdapter(context, audioArrayList);
                audioListView.setAdapter(audioListAdapter);
                audioListView
                        .setOnItemClickListener(new AudioListItemClickListener(
                                context, audioArrayList));

            }
        }

        @Override
        protected void onPause() {
            super.onPause();
            overridePendingTransition(0, 0);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            UtilityClass.removeActivityOnFinish(this);
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
            finish();
        }

    }

答案 1 :(得分:0)

获取ALBUM_ART的非常简单的代码。永远记住你应该读取存储权限。

        final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;

        final Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        while (cursor.moveToNext()) {
            final String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST));
            final String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
            final String albumart = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART));
            arrayList.add(artist);
        }