Retrieve images for songs android - android

I want to retrieve images for all songs in my list but i am getting only one image for all songs. Please tell me where i am wrong.
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = musicResolver.query(musicUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int titleColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
Long albumId = cursor.getLong(cursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
int artistColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
do {
Songs song = new Songs();
song.id = cursor.getLong(idColumn);
song.title = cursor.getString(titleColumn);
song.artist = cursor.getString(artistColumn);
Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,
albumId);
song.imagePath = albumArtUri;
songList.add(song);
} while (cursor.moveToNext());
}
}
I am trying to put it in listview so here is adapter:-
public View getView(int arg0, View arg1, ViewGroup arg2) {
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.cust_list_song, arg2, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
ImageView imageSong = (ImageView) songLay.findViewById(R.id.song_cover);
Songs currSong = songs.get(arg0);
songView.setText(currSong.title);
artistView.setText(currSong.artist);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(
c.getContentResolver(), currSong.imagePath);
bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
imageSong.setImageBitmap(bitmap);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
songLay.setTag(arg0);
return songLay;
}
I am beginner to this, so need help.

As I can see in your code, that's obvious result since you use the album's image instead of song image
Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,
albumId);
song.imagePath = albumArtUri;// You set the album art uri as song's image path

Related

Album art for song is not showing correct in android

Here is my cursor by which I m getting songs from local storage :
cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,MediaStore.Audio.AudioColumns.DURATION+">0", null, sortOrder);
I m displaying album by using another cursor like this shown below because I m not able to do this using same cursor :
ContentResolver musicResolve = getContentResolver();
Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor musicCursorTogetAlbum =musicResolve.query(smusicUri,null, null, null, null);
I m displaying album like this but it doesn't display correctly :
musicCursorTogetAlbum.moveToFirst();
musicCursorTogetAlbum.move(cursorPosition);
int x = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
int id_albumCursor = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
String thisArt = musicCursorTogetAlbum.getString(x);
Bitmap bm = BitmapFactory.decodeFile(thisArt);
Bitmap bm_temp = BitmapFactory.decodeFile(thisArt);
Drawable dr = new BitmapDrawable(getResources(), bm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
iv_album_art.setImageBitmap(bm);
}
And cursorPosition is the int type variable which gives position of cursor of cursor which I m using for getting song from local storage.
You can use this method to get album art of songs :
`
public static Bitmap getAlbumart(Context context, Long album_id){
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try{
final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null){
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
pfd = null;
fd = null;
}
} catch(Error ee){}
catch (Exception e) {}
return bm;
}
`

Extract photos from gallery android

I am using this code to extract photos(id ,date), but I don't know how can I access to the photo (bitmap) so I can show it!!
//extract photo's informations
public ArrayList<Image> checkGallerieFiles(){
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATA
};
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(uri, projection, "",null, "");
if (cur.moveToFirst()) {
while (cur.moveToNext())
{
Image newImage = new Image ();
newImage.setImageName(cur.getString(cur.getColumnIndex(MediaStore.Images.Media._ID)));
newImage.setImageDate(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN)));
myImageList.add(newImage);
}
}
return (myImageList);
}
This is my code. You get all images I just fetch file path then my second function will give you image bitmap from file path.
private void getallimages(File dir)
{
String[] STAR = { "*" };
controller.images.clear();
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();//this is my wrapper class
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default this it do for check box unselect u dont need to fill this
controller.images.add(imageItem);//this i just add all info in wrapper class
}
}
}
getbitmap from filepath
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}

How can I display Album Art using MediaStore.Audio.Albums.ALBUM_ART?

I'm trying to build a MP3 player and I want the ImageView to display the album art of respective songs. I've tried the following, but it doesn't work.
albumcover = (ImageView) findViewById(R.id.cover);
String coverPath = songsList.get(songIndex).get(MediaStore.Audio.Albums.ALBUM_ART);
Drawable img = Drawable.createFromPath(coverPath);
albumcover.setImageDrawable(img);
When I try to play the songs, all I get is a blank screen in the ImageView.
Here's how I get album art for a song:
Cursor cursor = getContentResolver().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(albumId)},
null);
if (cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
// do whatever you need to do
}
albumId refers to MediaStore.Audio.Media.ALBUM_ID for that song.
If you're are looking for album art for a particular song (rather than in a list of albums), as far as I know it's a two-stage process since ALBUM_ART is a property of MediaStore.Audio.Albums and is not available directly as song metadata.
If you have album ID you get Album Image uri :-
final public static Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(PlayerConstants.sArtworkUri,
listOfAlbums.get(position).getAlbumID());
And if you have a Image uri you can use any of the image loader Glide, Picaso, UIL to display images .
**OR**
you can write your own image loader
public Bitmap getAlbumart(Context context, Long album_id) {
Bitmap albumArtBitMap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try {
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
albumArtBitMap = BitmapFactory.decodeFileDescriptor(fd, null,
options);
pfd = null;
fd = null;
}
} catch (Error ee) {
} catch (Exception e) {
}
if (null != albumArtBitMap) {
return albumArtBitMap;
}
return getDefaultAlbumArtEfficiently(context.getResources());
}
public Bitmap getDefaultAlbumArtEfficiently(Resources resource) {
if (defaultBitmapArt == null) {
defaultBitmapArt = decodeSampledBitmapFromResource(resource,
R.drawable.default_album_art, UtilFunctions
.getUtilFunctions().dpToPixels(85, resource),
UtilFunctions.getUtilFunctions().dpToPixels(85, resource));
}
return defaultBitmapArt;
}
ContentResolver musicResolve = getContentResolver();
Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor music =musicResolve.query(smusicUri,null //should use where clause(_ID==albumid)
,null, null, null);
music.moveToFirst(); //i put only one song in my external storage to keep things simple
int x=music.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ART);
String thisArt = music.getString(x);
Bitmap bm= BitmapFactory.decodeFile(thisArt);
ImageView image=(ImageView)findViewById(R.id.image);
image.setImageBitmap(bm);
This method return ArrayList with song path and album art.
public static ArrayList<CommonModel> getAllMusicPathList(Context context) {
ArrayList<CommonModel> musicPathArrList = new ArrayList<>();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursorAudio = context.getContentResolver().query(songUri, null, null, null, null);
if (cursorAudio != null && cursorAudio.moveToFirst()) {
Cursor cursorAlbum;
if (cursorAudio != null && cursorAudio.moveToFirst()) {
do {
Long albumId = Long.valueOf(cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
cursorAlbum = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=" + albumId, null, null);
if(cursorAlbum != null && cursorAlbum.moveToFirst()){
String albumCoverPath = cursorAlbum.getString(cursorAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
String data = cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.DATA));
musicPathArrList.add(new CommonModel(data,albumCoverPath ,false));
}
} while (cursorAudio.moveToNext());
}
}
return musicPathArrList;
}
this is CommonModel .
public class CommonModel {
private String path;
private boolean selected;
public String getAlbumCoverPath() {
return albumCoverPath;
}
public void setAlbumCoverPath(String albumCoverPath) {
this.albumCoverPath = albumCoverPath;
}
private String albumCoverPath;
public CommonModel(String path, String albumCoverPath, boolean b) {
this.path = path;
this.albumCoverPath=albumCoverPath;
this.selected=b;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
selected = selected;
}
}
You should use Uri.parse("content://media/external/audio/albumart"); to query the albumart. the 1st answer may get exception on some phone (at least mine)
The below code worked for me. I know it has been answered already, it may be useful for someone checking for reference.
public void getAlbumArt() {
try {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor cursor = cr.query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int albumart = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
do {
String Albumids = cursor.getString(albumart);
Albumid.add(Albumids);
} while (cursor.moveToNext());
}cursor.close();
} catch (NumberFormatException e){
e.printStackTrace();
}
}
public void getSelectedPath(){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String path= String.valueOf(listView.getItemAtPosition(i));
if(path.equals("null")){
ImageView imgv=(ImageView)view.findViewById(R.id.imageView);
imgv.setImageResource(R.drawable.unknowalbum);
imgv.setMaxHeight(50);
imgv.setMaxWidth(50);
}
else{
Drawable image=Drawable.createFromPath(path);
ImageView imgview=(ImageView)view.findViewById(R.id.imageView);
imgview.setImageDrawable(image);
}
}
});
}
for complete code visit http://vasistaguru.blogspot.com/2017/02/get-albumart-and-trackname-using.html
Example Code
public static Uri getAlbumArtUri(long albumId) {
return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
}
ArrayList<Uri> albumArtUris = new ArrayList<>();
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{"album_id"}, null, null, null);
cursor.moveToFirst();
do {
long ablumId = cursor.getLong(cursor.getColumnIndexOrThrow("album_id"));
albumArtUris.add(getAlbumArtUri(ablumId));
} while (cursor.moveToNext());

select thumbnail from android gallery

I know how to get a photo from gallery in android
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PHOTO_REQUEST_CODE);
But how would I specifically select a thumbnail?
REASON FOR BOUNTY:
I have already tried both solutions at Get thumbnail Uri/path of the image stored in sd card + android . They don't work for me. I don't know how to get selectedImageUri, which is of type long, from data in
onActivityResult(int requestCode, int resultCode, Intent data)
String fn = ...; // file name
ContentResolver cr = ctx.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID
}, MediaColumns.DATA + "=?", new String[]{ fn }, null);
if(c!=null) {
try{
if(c.moveToNext()) {
long id = c.getLong(0);
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
}
}finally{
c.close();
}
}
If you have its cursor in hand, you can get its ID as ,
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Reffer the following code
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
So, for thumbnail,
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cursor, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
Hey so if everything else isn't working for you here is an easy way to make your own thumbnail if you have the Bitmap. If you don't know how to load the Bitmap from the Uri:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Here is the code to make a nice formatted thumbnail:
final int THUMBNAIL_HEIGHT = 75;//48
final int THUMBNAIL_WIDTH = 75;//66
Float width = new Float(bitmap.getWidth());
Float height = new Float(bitmap.getHeight());
Float ratio = width/height;
bitmap = Bitmap.createScaledBitmap(bitmap, (int)(THUMBNAIL_HEIGHT*ratio), THUMBNAIL_HEIGHT, false);
int padding = (THUMBNAIL_WIDTH - bitmap.getWidth())/2;
image.setPadding(padding, padding, padding, padding);
image.setBackgroundColor(0);
image.setImageBitmap(bitmap);
In this code "image" is the variable for the ImageView. I hope this helps some :D

How to get album art from a song file in android

how to get album art (i.e image file ) from a song file , i am able to get the album art of a file which is in music folder , but how to get ,when the music file is in different path other than music folder
Please any suggestion . Thanks in advance
use this code :)
private Bitmap getAlbumImage(String path) {
android.media.MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(path);
byte[] data = mmr.getEmbeddedPicture();
if (data != null) return BitmapFactory.decodeByteArray(data, 0, data.length);
return null;
}
First get the list of all songs from media store.
public void getSongList() {
// retrieve song info
ContentResolver res = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = res.query(musicUri, null, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
// get columns
int titleColumn = cursor.getColumnIndex(MediaColumns.TITLE);
int idColumn = cursor.getColumnIndex(BaseColumns._ID);
int artistColumn = cursor.getColumnIndex(AudioColumns.ARTIST);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
// add songs to list
do {
long thisId = cursor.getLong(idColumn);
String pathId = cursor.getString(column_index);
Log.d(this.getClass().getName(), "path id=" + pathId);
metaRetriver.setDataSource(pathId);
try {
art = metaRetriver.getEmbeddedPicture();
Options opt = new Options();
opt.inSampleSize = 2;
songImage = BitmapFactory .decodeByteArray(art, 0, art.length,opt);
}
catch (Exception e)
{ imgAlbumArt.setBackgroundColor(Color.GRAY);
}
String thisTitle = cursor.getString(titleColumn);
String thisArtist = cursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist,songImage));
} while (cursor.moveToNext());
}
Then after getting song list you can use song.getsongImage();
Bitmap bm= BitmapFactory.decodeFile(song.getsongImage());
ImageView image=(ImageView)findViewById(song.getsongImage());

Categories

Resources