Search code examples
androidlibgdx

USE an image from Android's built-in Gallery app programmatically


I took a look at this post: Get/pick an image from Android's built-in Gallery app programmatically

I think I understand what´s going on but from what I can see he never "uses" the selected image? I need the selected image to be drawn on a certain Screen.

I´ve done this so far:

public void onActivityResult(int request, int response, Intent data) {
    super.onActivityResult(request, response, data);

    if(response == RESULT_OK) {
        if(request == SELECT_PICTURE) {
            Uri selectedImage = data.getData();
            selectedImagePath = getPath(selectedImage);
            imageView.setImageURI(selectedImage);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitImage1 = BitmapFactory.decodeFile(selectedImagePath, options);
            imageView.setImageBitmap(bitImage1);
            imageBoolean = true;

        }
    }
}
public String getPath(Uri uri) {
    // just some safety built in
    if( uri == null ) {
        // TODO perform some logging or show user feedback
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    // this is our fallback here
    return uri.getPath();
}
@Override
 public void draw() {
    Canvas canvas = new Canvas();
    canvas.drawBitmap(bitImage1, 0.0f, 0.0f, null);
}
@Override
public void imageUpload() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            intent.setType("image/");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);

        }
    });

}

I call that method imageUpload() on a button in my screen class, which brings up the gallery, then I press an image and get this error:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/6865 (has extras) }} to activity {com.package.android/package.android.AndroidLauncher}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference

this is my screen class where I need the image to be drawn:

public class EditScreen implements Screen, purchaseInterface {
public EditScreen(final Stor gam) {
public void render(float delta) {
....
....
}
public void show() {
boxImage1.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            imageUpload();


        }
    });
    if(returnImageSet()) {
        draw();
    }
@Override
public void imageUpload() {
    pInt.imageUpload();
}

EDIT:

public String getPath(Uri uri) {
    // just some safety built in
    if( uri == null ) {
        // TODO perform some logging or show user feedback
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    try {
        InputStream inputStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    // this is our fallback here
    return uri.getPath();
}

Solution

  • Your getPath() implementation will work on few Android devices, getting fewer by the day. A Uri is not a file.

    Use a ContentResolver and openInputStream() to get an InputStream for the Uri you are given in onActivityResult(). Then, use decodeStream() on BitmapFactory to get a Bitmap. Do all of this on a background thread.

    Or, use a third-party image loading library (e.g., Picasso, Universal Image Loader) that can do this work for you.