Android load photos from mobile storage to GridView

1.8k views Asked by At

I am writing this mobile app, on main screen there is a grid view which should display all the photos on the mobile device. And a button to take photos.

I already wrote the imageAdaptor, and now my app could display photos I put in the R.drawable folder.

But can I put all photos stored on the device instead? Including all the photos taken by this app.

Thanks in advance.

Here are my codes:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="12dp" />

<GridView
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:columnWidth="100dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:gravity="center"
    />

Main method:

public class MainActivity extends AppCompatActivity {

public final String APP_TAG = "PhotoApp";
public String photoFileName = "photo.jpg";

private Uri imageUri;


MarshMallowPermission marshMallowPermission = new MarshMallowPermission(this);

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_view);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    };



public Uri getFileUri(String fileName){
    Uri imageUri=null;
    String typestr = "/images/";
    // Get safe storage directory for photos
    File mediaStorageDir = new File(
            Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES).getPath(), typestr+fileName);



    // Create the storage directory if it does not exist
    if (!mediaStorageDir.getParentFile().exists() && !mediaStorageDir.getParentFile().mkdirs()) {
        Log.d(APP_TAG, "failed to create directory");
    }

            //creating a URI for the file we just created
            imageUri=Uri.fromFile(mediaStorageDir);


    return imageUri;


}


public void takePhoto(View v ){
    // Check permissions
    if (!marshMallowPermission.checkPermissionForCamera()
            || !marshMallowPermission.checkPermissionForExternalStorage()){
        marshMallowPermission.requestPermissionForCamera();
    }  else {

        // set file name, will pass to getFileUri to convert it into a URI
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        photoFileName = "IMG_"+timeStamp+".jpg";
        Uri file_uri = getFileUri(photoFileName);

        //just to print it to see if everything alright
        System.out.println(file_uri);

        //a intent specifically to start the android camera
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //a intent used in conjunction with the image/video taking, telling where (in URI formate ) where to store the picture taken
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, file_uri);


        // Start the image capture intent to take photo
        startActivityForResult(takePictureIntent, MY_PERMISSIONS_REQUEST_OPEN_CAMERA);



    }


}

}
*/

Adaptor:

public class ImageAdapter extends BaseAdapter {

private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

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

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

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(250, 250));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// references to our images
private Integer[] mThumbIds = {
        R.drawable.s1, R.drawable.s2,
        R.drawable.s4, R.drawable.s5,
        R.drawable.s6, R.drawable.s3,

};

}

1

There are 1 answers

2
M. Adil On

Here's the solution btw, sorry It took so long to I wasn't aware that others were waiting for the answer. Sorry. The relevant code is below.

This is AsyncTask that will query the device's MediaStore and retrieve all the photos. Note that this is retrieving the thumbnails and not the full size images, and more specifically it's the MICRO_KIND. There is also a Thumbnail.MINI_KIND as well.

 /*----------------------------ASYNC TASK TO LOAD THE     PHOTOS-------------
-------------------------------------------*/

public class LoadPhotos extends AsyncTask<Object, Object, Object> {

@Override
protected Object doInBackground(Object... params) {
    try {
        final String[] columns = { MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;

        Cursor imagecursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                null, null, orderBy);

        int image_column_index = imagecursor
                .getColumnIndex(MediaStore.Images.Media._ID);

        AllPhotosActivity.count = imagecursor.getCount();
        AllPhotosActivity.windows = new Bitmap[AllPhotosActivity.count];

        for (int i = 0; i < AllPhotosActivity.count; i++) {
            imagecursor.moveToPosition(i);
            // i = index;
            int id = imagecursor.getInt(image_column_index);
            windows[i] = MediaStore.Images.Thumbnails.getThumbnail(
                    getApplicationContext().getContentResolver(), id,
                    MediaStore.Images.Thumbnails.MICRO_KIND, null);
        }

        imagecursor.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("AllPhotosActivity",
                "Error occured while fetching all photos on device.");
    }
    return null;

}

@Override
protected void onPostExecute(Object result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    Handler mHandler = new Handler();

    mHandler.post(new Runnable() {

        public void run() {

            pd.dismiss();
            // imageAdapter.notifyDataSetChanged();
            // sdcardImages.setAdapter(imageAdapter);

        }

    });

    // pd.dismiss();
    imagegrid.setAdapter(imageAdapter);
    // pd.dismiss();

}

@Override
protected void onProgressUpdate(Object... values) {
    // TODO Auto-generated method stub
    super.onProgressUpdate(values);
}

}

Here's the adapter for the GridView that's going to bind your thumbnails to the gridview. My issue was simply in the getView method of my ImageAdapter, notice I'm setting my ImageView resources from different indexes of an array of Bitmaps I called windows.

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView i = (ImageView) convertView;
    if (i != null) {
        i.setImageBitmap(windows[position]);
    } else {
        i = new ImageView(mContext.getApplicationContext());
        // i.setPadding(3, 3, 3, 3);
        // i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setAdjustViewBounds(true);
        // i.setMaxHeight(200);
        // i.setMaxWidth(200);
        i.setPadding(3, 3, 3, 3);
        i.setLayoutParams(new GridView.LayoutParams(92, 92));
        i.setImageBitmap(windows[position]);

    }
    return i;
}

public int getCount() {
    // TODO Auto-generated method stub
    return count;
}
}