Search code examples
androidandroid-gallerymediastore

How to get images in gallery on android phone?


I want to get images in phone gallery and show on gridview. I use Cursor:

final String[] columns = {MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
Cursor imagecursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);

My phone doesn't have SD card, I got Unfortunately app has stopped error. When I replace EXTERNAL_CONTENT_URI with INTERNAL_CONTENT_URI, nothing happened no errors, no images displayed.


Solution

  • you can get images by initiating this intent:

    Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    

    then handle it in onActivityResult()

         @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == SELECT_FILE)
                    onSelectFromGalleryResult(data);
    }
    }
    
    private void onSelectFromGalleryResult(Intent data) {
    
        if (data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    let me know if it help you