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.


19 comments:

  1. Thanks for your ideas. You can also find the details on Affity Solutions, at the C++ Developers. The main object of the Affity Solutions is to provide quality web services and is among the few software development company in Nagpur.

    ReplyDelete
  2. Embedded system training: Wiztech Automation Provides Excellent training in embedded system training in Chennai - IEEE Projects - Mechanical projects in Chennai Wiztech provide 100% practical training, Individual focus, Free Accommodation, Placement for top companies. The study also includes standard microcontrollers such as Intel 8051, PIC, AVR, ARM, ARMCotex, Arduino etc.

    Embedded system training in chennai
    Embedded Course training in chennai
    Matlab training in chennai
    Android training in chennai
    LabVIEW training in chennai
    Arduino training in chennai
    Robotics training in chennai
    Oracle training in chennai
    Final year projects in chennai
    Mechanical projects in chennai
    ece projects in chennai

    ReplyDelete
  3. WIZTECH Automation, Anna Nagar, Chennai, has earned reputation offering the best automation training in Chennai in the field of industrial automation. Flexible timings, hands-on-experience, 100% practical. The candidates are given enhanced job oriented practical training in all major brands of PLCs (AB, Keyence, ABB, GE-FANUC, OMRON, DELTA, SIEMENS, MITSUBISHI, SCHNEIDER, and MESSUNG)

    PLC training in chennai
    Automation training in chennai
    Best plc training in chennai
    PLC SCADA training in chennai
    Process automation training in chennai
    Final year eee projects in chennai
    VLSI training in chennai

    ReplyDelete
  4. Wiztech Automation is the Leading Best IEEE Final year project Centre in Chennai and the final year students are provided complete guidance and support in their final year projects. The IEEE projects in Chennai that Wiztech Automation offers guidance and support for include complete range of system domains – such as PLC projects, embedded projects, VLSI projects, software projects, IT projects, Civil projects. Students looking for specific projects pertaining to departments of ECE, EEE, E&I, Mechanical, Mechatronics, bio-medical, IT, Computer, Civil projects in B.E, M.E, B.Tech, M.Tech, B.SC., and M.Sc Electronics, could also get turnkey solutions at Wiztech Automation Solutions to turn out successful project outcomes and models. Since the students at Wiztech Automation gain thorough theoretical and practical knowledge and skills as they pursue their final year projects and develop 2015 and 2016 Latest IEEE Projects portraying them well.

    Final year projects in chennai
    Mechanical projects in chennai
    ece projects in chennai
    Final year eee projects in chennai
    VLSI project center in chennai
    Industrial projects in chennai
    Fianl year CSE projects in chennai

    ReplyDelete
  5. 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
  6. 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
  7. 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
  8. 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
  9. using above code WhatsApp images are displayed.

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

    Google App Integration Chennai

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

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

    ReplyDelete
  13. Good work…unique site and interesting too… keep it up…looking forward for more updates.
    Web Designing Company in Bangalore, Web Development Company Bangalore

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

    ReplyDelete

  15. Nice Sharing..! I have been following you for a couple of months now but this is my first time commenting on a blog post. Thank you for sharing your knowledge and experience with us. Keep up the good work. Already bookmarked for future reference.

    Installment loans in Mississippi
    Payday loans in Mississippi
    Title loans in Mississippi

    ReplyDelete


  16. 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
  17. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well

    as giving..
    Mobile App Development Company
    Mobile App Development Company in India
    Mobile App Development Companies

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

    ReplyDelete
  19. 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