Getting an image into a GridView

  • Replies:0
James Whelan
  • Forum posts: 1

Aug 17, 2015, 11:46:56 AM via Website

I've been trying to load an image from an SD card and place it into a GridView.

When the images are placed in the drawable folder, they appear fine. But how would I go about including an image loaded by the user from the phone's gallery?

This is the code I'm working on at the moment:

package com.example.jameswhelan.gridview;




public class MainActivity extends Activity {

private static int RESULT_LOAD_IMG = 1;
public int queue=-1;

// String for image name and image URI variables declared in main class, outside any methods.
String imgDecodableString;
Uri selectedImage;

ArrayList<String> itemList = new ArrayList<String>();

Button browseGalleryButton;
TextView tv;

Integer[] imageIDs = {

};


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

    browseGalleryButton = (Button)findViewById(R.id.browseGalleryButton);
    tv = (TextView)findViewById(R.id.uriText);

    browseGalleryButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent();
            // Start the Intent

            // Create a new intent called galleryIntent and call the setType() method to all images.
            galleryIntent.setType("image/*");
            // Call the putExtra() method and set the EXTA_ALLOW_MULTIPLE flag to true.
            // This *should* allow us to select multiple images from the gallery.
            galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            // Call the setAction() method on the intent to fetch the required data.
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

            // Finally, call the startActivityForResult() method, passing it the Intent created above.
            startActivityForResult(Intent.createChooser(galleryIntent, "WANG"), 1);

        }
    });



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

    gridView.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent,
                                View v, int position, long id)
        {
            Toast.makeText(getBaseContext(),
                    "pic" + (position + 1) + " selected",
                    Toast.LENGTH_SHORT).show();
        }
    });
}




@Override
// OnActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Set up a try/catch for selecting images from the gallery.
    try {

        // If an image *is* selected, i.e. we make sure the user has actually selected one.
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {

            // Set
            queue = 1;

            //Assign the results of data.GetData() to our URI variable, selectedImage.
            selectedImage = data.getData();

            // Set up a string to contain the name of the file in question.
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor,
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

            // Move the cursor to the first row.
            cursor.moveToFirst();

            // ???? something to do with a database
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            tv.setText(imgDecodableString);



        }

        // Stop the "You haven't picked an image!" message on displaying if we hit the back button
        // to return to the Browse Photos screen from the Edit Photos screen.

        else if(queue!=-1) {

            return;
        }

        else {

            Toast.makeText(this, "You haven't picked an image!",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong!", Toast.LENGTH_LONG).show();
    }



}// end onActivityResult


public class ImageAdapter extends BaseAdapter
{
    private Context context;

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

    //---returns the number of images---
    public int getCount() {
        return imageIDs.length;
    }

    //---returns the ID of an item---
    public Object getItem(int position) {
        return position;
    }

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

    //---returns an ImageView view---
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(5, 5, 5, 5);
        } else {
            imageView = (ImageView) convertView;
        }

        itemList.add(imgDecodableString);
        Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
        imageView.setImageBitmap(bm);
        return imageView;
    }
}// end image adapter

public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

    Bitmap bm = null;
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(path, options);

    return bm;
}

public int calculateInSampleSize(

        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }

    return inSampleSize;
}



}// end main activity

The integer array imageIDs was previously populated with image names from the drawable folder so how would I go about including an image loaded from the gallery into the GridView?

Reply