Thursday 16 October 2014

This blog useful for display album list for image and video

Some times we need to display album wise image and video in android application.
I have made one sample example for this functionality.
I would like to share this example.This might be useful too you.

Below Android api used for display album wise images and videos.

Image API:

MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

Video API:
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;


Features included in example:
  • Album list fetch and display with count
  • Video thumbnail display with duration
  • Image and Video thumbnail display for selected album
  • Get selected image/video path





Code Snippets:

1.) This method used for fetch image album list.

    private void getPhotoList() {

       

        String[] PROJECTION_BUCKET = { ImageColumns.BUCKET_ID,

                ImageColumns.BUCKET_DISPLAY_NAME, ImageColumns.DATE_TAKEN,

                ImageColumns.DATA };

      

        String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";

        String BUCKET_ORDER_BY = "MAX(datetaken) DESC";



      

        Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;



        Cursor cur = getContentResolver().query(images, PROJECTION_BUCKET,

                BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);



     

        GalleryPhotoAlbum album;



        if (cur.moveToFirst()) {

            String bucket;

            String date;

            String data;

            long bucketId;



            int bucketColumn = cur

                    .getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);



            int dateColumn = cur

                    .getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);

            int dataColumn = cur.getColumnIndex(MediaStore.Images.Media.DATA);



            int bucketIdColumn = cur

                    .getColumnIndex(MediaStore.Images.Media.BUCKET_ID);



            do {

                // Get the field values

                bucket = cur.getString(bucketColumn);

                date = cur.getString(dateColumn);

                data = cur.getString(dataColumn);

                bucketId = cur.getInt(bucketIdColumn);



                if (bucket != null && bucket.length() > 0) {

                    album = new GalleryPhotoAlbum();

                    album.setBucketId(bucketId);

                    album.setBucketName(bucket);

                    album.setDateTaken(date);

                    album.setData(data);

                    album.setTotalCount(photoCountByAlbum(bucket));

                    arrayListAlbums.add(album);

                    // Do something with the values.

                    Log.v("ListingImages", " bucket=" + bucket

                            + "  date_taken=" + date + "  _data=" + data

                            + " bucket_id=" + bucketId);

                }



            } while (cur.moveToNext());

        }

        cur.close();

          } 




2.) This method used for retrieve image count album wise.

    private int photoCountByAlbum(String bucketName) {

        try {

            final String orderBy = MediaStore.Images.Media.DATE_TAKEN;

            String searchParams = null;

            String bucket = bucketName;

            searchParams = "bucket_display_name = \"" + bucket + "\"";



            // final String[] columns = { MediaStore.Images.Media.DATA,

            // MediaStore.Images.Media._ID };

            Cursor mPhotoCursor = getContentResolver().query(

                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,

                    searchParams, null, orderBy + " DESC");



            if (mPhotoCursor.getCount() > 0) {

                return mPhotoCursor.getCount();

            }

            mPhotoCursor.close();

        } catch (Exception e) {

            e.printStackTrace();

        }



        return 0;



    }
 
3.) This method used for retrieve albumwise image list.
private void initPhotoImages(String bucketName) {

        try {

            final String orderBy = MediaStore.Images.Media.DATE_TAKEN;

            String searchParams = null;

            String bucket = bucketName;

            searchParams = "bucket_display_name = \"" + bucket + "\"";



            // final String[] columns = { MediaStore.Images.Media.DATA,

            // MediaStore.Images.Media._ID };

            mPhotoCursor = getContentResolver().query(

                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,

                    searchParams, null, orderBy + " DESC");



            if (mPhotoCursor.getCount() > 0) {



                cursorData = new ArrayList<MediaObject>();



                cursorData.addAll(Utils.extractMediaList(mPhotoCursor,

                        MediaType.PHOTO));         

            }

            // setAdapter(mImageCursor);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
 
For Video you have to change only video uri in above queries.

You can download source code from Github.


68 comments:

  1. Good Tutorial..U saved my time...but in this scenario whatsapp images is not getting while its opening..plz fix this and post that updated status..
    Thank you

    ReplyDelete
  2. Super idea ,
    And i have click event in gridview but i don't know about how to get the those path name so please help me

    ReplyDelete
  3. Good Tutorial..U saved my time...but in this scenario whatsapp images is not getting while its opening..plz fix this and post that updated status..

    ReplyDelete
  4. Paste below code in ProcessGalleryFile

    public class ProcessGalleryFile extends AsyncTask {

    private static int WIDTH = 120;
    private static int HEIGHT = 120;

    ImageView photoHolder;
    TextView durationHolder;
    MediaType type;
    String filePath;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    public ProcessGalleryFile(ImageView photoHolder, TextView durationHolder, String filePath, MediaType type) {
    HEIGHT = WIDTH = (int) photoHolder.getContext().getResources().getDimension(R.dimen.thumbnail_width);
    this.filePath = filePath;
    this.durationHolder = durationHolder;
    this.photoHolder = photoHolder;
    this.type = type;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {

    Bitmap bmp = null;
    Log.d(getClass().getSimpleName(), "" + Thread.getAllStackTraces().keySet().size());
    if (type != MediaType.PHOTO) {
    try {
    bmp = ImageLoader.getInstance().getMemoryCache().get(Uri.fromFile(new File(filePath)).toString() + "_");
    } catch (Exception e) {
    Log.e(ProcessGalleryFile.class.getSimpleName(), "" + e);
    }
    if (bmp == null) {
    try {
    bmp = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
    if (bmp != null) {
    ImageLoader.getInstance().getMemoryCache().put(Uri.fromFile(new File(filePath)).toString() + "_", bmp);
    }
    } catch (Exception e) {
    Log.e(getClass().getSimpleName(), "Exception when rotating thumbnail for gallery", e);
    } catch (OutOfMemoryError e) {
    Log.e(ProcessGalleryFile.class.getSimpleName(), "" + e);
    }
    }
    }
    return bmp;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
    super.onPostExecute(result);
    if (type == MediaType.PHOTO) {
    durationHolder.setVisibility(View.GONE);
    ImageAware aware = new ImageViewAware(photoHolder) {

    @Override
    public int getWidth() {
    return WIDTH;
    }

    @Override
    public int getHeight() {
    return HEIGHT;
    }
    };

    final String uri = Uri.fromFile(new File(filePath)).toString();
    final String decoded = Uri.decode(uri);

    ImageLoader.getInstance().displayImage(decoded, aware, ImageOption.GALLERY_OPTIONS.getDisplayImageOptions());
    } else {
    durationHolder.setText(Utils.getDurationMark(filePath, retriever));
    durationHolder.setVisibility(View.VISIBLE);
    photoHolder.setImageBitmap(result);
    }
    }

    @Override
    public int hashCode() {
    return filePath != null ? filePath.hashCode() : super.hashCode();
    }

    @Override
    public boolean equals(Object o) {
    if (o == null || !(o instanceof ProcessGalleryFile)) return false;
    ProcessGalleryFile file = (ProcessGalleryFile) o;
    return filePath != null && file.filePath != null && filePath.equals(file.filePath);
    }
    }





    ReplyDelete
  5. using above code WhatsApp images are displayed.

    ReplyDelete
  6. Wonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!

    Google App Integration Chennai

    ReplyDelete
  7. Most useful project on google about android gallery related.

    ReplyDelete
  8. what should do after get images of album to get selected image into other activity and get details of it

    ReplyDelete
  9. good example ....but how to get video name....

    ReplyDelete


  10. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
    please sharing like this information......
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  11. Very nice article this would definitely help the beginners, coding made easy with the help of example you shared...Android Training in Bangalore

    ReplyDelete
  12. Really it was an awesome article...very interesting to read..
    sharing like this information......
    Live Royal Rumble 2018
    check Plus 2 Result
    Live Streaming IPL 2018

    ReplyDelete
  13. Great Post, I really appreciate your effort here. We could surely use it for some help. In addition I would like to share an article.
    wordpress development sydney | android app developer sydney

    ReplyDelete
  14. i like it ,,,but i am going to develop Video Player and I wanna show Album list with Images And Total number of videos in each album,
    my Code is


    public class MainActivity extends Activity {
    private Cursor audiocursor;
    private int audio_column_index;
    ListView audiolist;
    int count;
    int album = 1;

    int dura;
    int i1 = R.drawable.audio_track;


    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init_phone_videos_grid();


    }

    @SuppressWarnings("deprecation")
    private void init_phone_videos_grid() {
    System.gc();

    final String[] projection = new String[]{ "DISTINCT " +MediaStore.Video.VideoColumns.ALBUM};

    final String sortOrder = MediaStore.Video.VideoColumns.ALBUM + " COLLATE LOCALIZED ASC";

    audiocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,projection, null, null, sortOrder);


    count = audiocursor.getCount();
    audiolist = (ListView) findViewById(R.id.PhoneVideo);
    audiolist.setAdapter(new AudioAdapter(getApplicationContext()));

    audiolist.setOnItemClickListener(videogridlistener);

    }

    private AdapterView.OnItemClickListener videogridlistener = new AdapterView.OnItemClickListener() {
    @SuppressWarnings("rawtypes")
    public void onItemClick(AdapterView parent, View v, int position, long id) {

    //Toast.makeText(MainActivity.this, "music will be available shortly" , Toast.LENGTH_SHORT).show();

    System.gc();
    audio_column_index = audiocursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM);

    audiocursor.moveToPosition(position);

    String filename = audiocursor.getString(audio_column_index);

    Intent intent = new Intent(MainActivity.this, AlbumVideoDetail.class);

    intent.putExtra("albumfilename", filename);
    intent.putExtra("album", album);

    startActivity(intent);

    }
    };


    public class AudioAdapter extends BaseAdapter {
    private Context vContext;
    CheckBox cb;
    int position = 0;
    int check = 0;
    String a[] = new String[count];

    public AudioAdapter(Context c) {
    vContext = c;
    }

    public int getCount() {
    return count;
    }

    public Object getItem(int position) {
    return position;
    }

    public long getItemId(int position) {
    return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
    System.gc();
    LayoutInflater inflater = getLayoutInflater();

    View row;

    row = inflater.inflate(R.layout.list_item1, parent, false);

    final TextView title = (TextView) row.findViewById(R.id.txt);

    title.setTextColor(Color.parseColor("#000000"));

    if (convertView == null) {

    audio_column_index = audiocursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM);
    audiocursor.moveToPosition(position);
    String TITLE = audiocursor.getString(audio_column_index);
    String a[] = new String[count];
    //Toast.makeText(MainActivity.this, "music will be available shortly" + TITLE, Toast.LENGTH_SHORT).show();


    title.setText(TITLE);

    }

    return (row);
    }


    }
    }

    ReplyDelete
  15. Any Body Can Help Me Please .

    ReplyDelete
  16. Thanks For Your valuable posting, it was very informative...
    Android App Developer Sydney

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Interesting blog post. This blog shows that you have a great future as a content writer. Waiting for more updates...
    Blue prism Training in Chennai | RPA Training in Chennai

    ReplyDelete
  19. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging

    java training in chennai | java training in bangalore


    java training in tambaram | java training in velachery

    ReplyDelete
  20. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Devops training in sholinganallur

    ReplyDelete
  21. I have read your blog and I gathered some needful information from your blog. Keep update your blog. Java Training in Chennai | Python Training in Chennai

    ReplyDelete
  22. UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
    ui path training in bangalore

    ReplyDelete
  23. The site was so nice, I found out about a lot of great things. I like the way you make your blog posts. Keep up the good work and may you gain success in the long run.
    python training in velachery
    python training institute in chennai

    ReplyDelete
  24. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers


    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  25. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    safety course institute in chennai

    ReplyDelete
  26. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips to help him learn and master in Angularjs. I like your writing style and I hope you will keep doing this good working.
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Angularjs Institute in Bangalore
    Android Classes in Bangalore
    Android Development Training in Bangalore
    Android Development Course in Bangalore

    ReplyDelete
  27. Nice Post. Looking for more updates from you. Thanks for sharing.

    Article submission sites
    Education

    ReplyDelete
  28. I think things like this are really interesting. I absolutely love to find unique places like this. It really looks super creepy though!! R Programming Interview Questions and Answers | Trending Software Technologies in 2018 | R Programming Online Training course

    ReplyDelete
  29. Your blog is so inspiring for the young generations.thanks for sharing your information with us and please update more new ideas.
    german learning classes in bangalore
    german coaching classes in bangalore
    German Course in Anna Nagar
    German Courses in T nagar

    ReplyDelete
  30. I appreciate that you produced this wonderful article to help us get more knowledge about this topic. I know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  31. marvellous!i really want to say that everyone will get new thoughts after read your post and you have narrated beautiful ideas
    Android Training in Chennai
    Android Course in Chennai
    SEO Training in Chennai
    Android Training in Chennai
    Android Training in Velachery

    ReplyDelete
  32. I Got Job in my dream company with decent 12 Lacks Per Annum Salary, I have learned this world most demanding course out there in the current IT Market from the Data Science Course in Bangalore Providers who helped me a lot to achieve my dreams comes true. Really worth trying.

    ReplyDelete
  33. Today Telugu news updates provide us the information of breaking news and live updates. we get live news, political, education, technology, etc. Today Telugu news gives the best news updates. It also keeps its readers informed about the latest happenings in the world with instant updates.

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. Great Post. The information provided is of great use as I got to learn new things. Keep Blogging.Best Android Training Institute


    ReplyDelete
  36. Really i appreciate the effort you made to share the knowledge. The topic here i found was really effective...

    Learn SAP from the Industry Experts we bridge the gap between the need of the industry. eTechno Soft Solutions provide the Best IT Training in Bangalore .

    ReplyDelete
  37. Thanks for sharing the very useful info,Really Very Informative Blog. oracle training in chennai

    ReplyDelete



  38. Nice article and thanks for sharing with us. Its very informative





    Tableau Training in Hyderabad

    ReplyDelete


  39. Nice article and thanks for sharing with us. Its very informative



    Plots in PHARMA CITY

    ReplyDelete
  40. Infycle Technologies, one of the best software training institutes in Chennai offers excellent Oracle PLSQL training in Chennai for freshers and students, and Tech Professionals of any field. Other demanding courses such as Java, Hadoop, Selenium, Big Data, Android, and iOS Development will also be trained with complete hands-on training. After the completion of training, the students will be sent for placement interviews in the core MNC's. Dial 7504633633 to get more info and a free demo.

    Excellent Oracle PLSQL Training Chennai | Infycle Technologies

    ReplyDelete
  41. Infycle Technologies, the top software training institute and placement center in Chennai offers the Best Digital Marketing course in Chennai for freshers, students, and tech professionals at the best offers. In addition to Digital Marketing, other in-demand courses such as DevOps, Data Science, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  42. Finish the Selenium Training in Chennai from Infycle Technologies, the best software training institute in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Java, Hadoop, Big Data, Android, and iOS Development, Oracle, etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete
  43. This is an informative post. Got a lot of info and details from here. Thank you for sharing this and looking forward to reading more of your post.
    meal kit delivery app development

    ReplyDelete
  44. Thank you for sharing this insightful blog post. I found it to be informative. The points you've raised are both relevant and well-researched. Visit to AWS Classes in Pune

    ReplyDelete