6

I want to display album art with album name in listview. But i am not getting the way to display album art. I have tried from cover art on android.

Here is my Code :

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();
}

But i am getting the album_id -1. So i am not getting album_id for album but i am having album song in my sdcard. And sdcard is having folder like albumthums which includes some files. So please give me solution to get album name and art. Thanx in Advance.


This is my error log :

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)
Community
  • 1
  • 1
Zankhna
  • 4,570
  • 9
  • 62
  • 103
  • Hey are you still working on the same project?? – Ankit Srivastava Aug 14 '13 at 10:27
  • @Ankit no i am not working on this project, but if u have any doubt then ask me.If possible, i'll try to solve it. – Zankhna Aug 14 '13 at 10:36
  • well i had no doubts i thought if you were still working i could share my code...... :) by the way have you ever used mediametadataretriever? or tried to sort custom listviews? – Ankit Srivastava Aug 14 '13 at 10:38
  • what metadata you want to retrive ? – Zankhna Aug 14 '13 at 10:41
  • well i have retrieved the songs info using the metadata....but i don't know how to display all the songs from a particular album/or artist http://stackoverflow.com/questions/18164413/how-to-get-songs-from-album-artist-in-android-using-mediametadataretriever – Ankit Srivastava Aug 14 '13 at 10:44
  • @Ankit No i haven't tried to sort custom listview. – Zankhna Aug 14 '13 at 10:44
  • @Ankit To retrieve song of particular album or artist, you will have to load all albums and onclick of that album, you can get songs of that particular album. For that, you will have to use `Mediastore` class. – Zankhna Aug 14 '13 at 10:52
  • yeah thats the thing i don't want to use mediastore.....becuase then i would be doing a single thing with two different approach...i have already used mediametadataretriever to display all the songs..now if i use mediastore there would be no purpose of using mediametadataretriever.. – Ankit Srivastava Aug 14 '13 at 10:55
  • @Ankit i have not used mediametadatretriever. – Zankhna Aug 14 '13 at 11:15

2 Answers2

25

use Below Code to get album art with song information. you can change slightly to display only album names instead of songs list.

 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();
        }

    }
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113
Mohd Mufiz
  • 2,236
  • 17
  • 28
  • 2
    Long albumId = cursor.getLong(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)); This returns -1. – Zankhna Dec 03 '12 at 07:12
  • every album has an id I am fetching that id from cursor – Mohd Mufiz Dec 03 '12 at 07:13
  • Returns the zero-based index for the given column name, or throws IllegalArgumentException if the column doesn't exist. If you're not sure if a column will exist or not use getColumnIndex(String) and check for -1, which is more efficient than catching the exceptions. ------------------------------------------------------------------- Run that in actual device which must having some albums in it – Mohd Mufiz Dec 03 '12 at 07:20
  • i am getting albumid but now i am getting error on bitmap = MediaStore.Images.Media.getBitmap( context.getContentResolver(), albumArtUri); – Zankhna Dec 03 '12 at 09:30
  • It throws runtime exception. – Zankhna Dec 03 '12 at 09:30
  • I have solved this null pointer exception. But now bitmap image is not set to imageview. It is getting null. – Zankhna Dec 03 '12 at 11:20
1

Very Simple code to get ALBUM_ART. Always remember you should have read storage permission.

        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);
        }
Razz
  • 452
  • 6
  • 9