How to make sort gallery thumbnails image by date

2019-02-15 23:17发布

问题:

I am developing an android applicaiton. This application get all thumbnail images from gallery. I want to sort these thumbnails by date, but I can't do it.

Please help me.

Get all images

// Set up an array of the Thumbnail Image ID column we want
String[] columns = {MediaStore.Images.Media._ID};

String orderBy = MediaStore.Images.Thumbnails._ID + " DESC LIMIT 10";

// Create the cursor pointing to the SDCard

cursor = getActivity().managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
        columns, // Which columns to return
        null,       // Return all rows
        null,
        orderBy);

// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

myGalleryImages = (GridView) view.findViewById(R.id.my_gallery);
myGalleryImages.setAdapter(new ImageAdapter(getActivity()));

set images

    // Move cursor to current position
    cursor.moveToPosition(position);
    // Get the current value for the requested column
    int imageID = cursor.getInt(columnIndex);
    // Set the content of the image based on the provided URI
    holder.image.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));

回答1:

Update columns and orderBy like this:

  String[] columns = {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.DATE_TAKEN};

  String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"; 

and see if that helps.

You could also fetch real images instead of thumbnails and use image loading library that will take care of proper re-sizing. In this case replace your Thumbnails references with ImageColumns



回答2:

this code will save the first 100 thumbs (SORTED by date)

      Cursor cursor = this.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null,       // Return all rows
                null,
                "image_id DESC");

// Get the column index of the Thumbnails Image ID
        int columnIndex = cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
        for(int i =0;i<cursor.getCount();i++){
            if (i==100) break;
            cursor.moveToPosition(i);
            mImagesFromGallery[i] = cursor.getString(columnIndex);
        }
        cursor.close();