Friday, June 8, 2012

Open an image in Android"s built-in Gallery app programmatically


I am trying to open an image / picture in the Gallery built-in app from inside my application.



I have a URI of the picture (the picture is located on the SD card).



Do you have any suggestions?



Thank you in advance.


Source: Tips4all

7 comments:

  1. This is a complete solution

    public class BrowsePicture extends Activity {

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById(R.id.Button01))
    .setOnClickListener(new OnClickListener() {

    public void onClick(View arg0) {

    // in onCreate or any event where your want the user to
    // select a file
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,
    "Select Picture"), SELECT_PICTURE);
    }
    });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    }
    }
    }

    public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
    }


    }

    ReplyDelete
  2. Here is an update to the fine code that hcpl posted. but this works with OI file manager, astro file manager AND the media gallery too (tested). so i guess it will work with every file manager (are there many others than those mentioned?). did some corrections to the code he wrote.

    public class BrowsePicture extends Activity {

    //YOU CAN EDIT THIS TO WHATEVER YOU WANT
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    //ADDED
    private String filemanagerstring;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById(R.id.Button01))
    .setOnClickListener(new OnClickListener() {

    public void onClick(View arg0) {

    // in onCreate or any event where your want the user to
    // select a file
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,
    "Select Picture"), SELECT_PICTURE);
    }
    });
    }

    //UPDATED
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
    Uri selectedImageUri = data.getData();

    //OI FILE Manager
    filemanagerstring = selectedImageUri.getPath();

    //MEDIA GALLERY
    selectedImagePath = getPath(selectedImageUri);

    //DEBUG PURPOSE - you can delete this if you want
    if(selectedImagePath!=null)
    System.out.println(selectedImagePath);
    else System.out.println("selectedImagePath is null");
    if(filemanagerstring!=null)
    System.out.println(filemanagerstring);
    else System.out.println("filemanagerstring is null");

    //NOW WE HAVE OUR WANTED STRING
    if(selectedImagePath!=null)
    System.out.println("selectedImagePath is the right one for you!");
    else
    System.out.println("filemanagerstring is the right one for you!");
    }
    }
    }

    //UPDATED!
    public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor!=null)
    {
    //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
    //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
    int column_index = cursor
    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
    }
    else return null;
    }

    ReplyDelete
  3. basis with the above code, I reflected the code like below, may be it's more suitable:

    public String getPath(Uri uri) {
    String selectedImagePath;
    //1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor != null){
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    selectedImagePath = cursor.getString(column_index);
    }else{
    selectedImagePath = null;
    }

    if(selectedImagePath == null){
    //2:OI FILE Manager --- call method: uri.getPath()
    selectedImagePath = uri.getPath();
    }
    return selectedImagePath;
    }

    ReplyDelete
  4. Assuming you have an image folder in your SD card directory for images only.

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    // tells your intent to get the contents
    // opens the URI for your image directory on your sdcard
    intent.setType("file:///sdcard/image/*");
    startActivityForResult(intent, 1);


    Then you can decide with what you would like to do with the content back in your activity.

    This was an example to retrieve the path name for the image, test this with your code just to make sure you can handle the results coming back. You can change the code as needed to better fit your needs.

    protected final void onActivityResult(final int requestCode, final int
    resultCode, final Intent i) {
    super.onActivityResult(requestCode, resultCode, i);

    // this matches the request code in the above call
    if (requestCode == 1) {
    Uri _uri = i.getData();

    // this will be null if no image was selected...
    if (_uri != null) {
    // now we get the path to the image file
    cursor = getContentResolver().query(_uri, null,
    null, null, null);
    cursor.moveToFirst();
    String imageFilePath = cursor.getString(0);
    cursor.close();
    }
    }


    My advice is to try to get retrieving images working correctly, I think the problem is the content of accessing the images on the sdcard. Take a look at Displaying images on sd card.

    If you can get that up and running, probably by the example supplying a correct provider, you should be able to figure out a work-around for your code.

    Keep me updated by updating this question with your progress. Good luck

    ReplyDelete
  5. package com.ImageConvertingDemo;

    import java.io.BufferedInputStream;
    import java.io.FileInputStream;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.EditText;
    import android.widget.ImageView;

    public class MyActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    EditText tv = (EditText)findViewById(R.id.EditText01);
    ImageView iv = (ImageView)findViewById(R.id.ImageView01);
    FileInputStream in;
    BufferedInputStream buf;
    try
    {
    in = new FileInputStream("/sdcard/smooth.png");
    buf = new BufferedInputStream(in,1070);
    System.out.println("1.................."+buf);
    byte[] bMapArray= new byte[buf.available()];
    tv.setText(bMapArray.toString());
    buf.read(bMapArray);
    Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);

    /*for (int i = 0; i < bMapArray.length; i++)
    {
    System.out.print("bytearray"+bMapArray[i]);
    }*/
    iv.setImageBitmap(bMap);
    //tv.setText(bMapArray.toString());
    //tv.setText(buf.toString());
    if (in != null)
    {
    in.close();
    }
    if (buf != null)
    {
    buf.close();
    }

    }
    catch (Exception e)
    {
    Log.e("Error reading file", e.toString());
    }
    }
    }

    ReplyDelete
  6. There are two useful tutorials about image picker with downloadable source code here:

    How to Create Android Image Picker

    How to Select and Crop Image on Android

    However, the app will be forced to close sometime, you can fix it by adding android:configChanges attribute into main activity in Manifest file like as:

    <activity android:name=".MainActivity"
    android:label="@string/app_name" android:configChanges="keyboardHidden|orientation" >


    It seems that the camera API lost control with orientation so this will help it. :)

    ReplyDelete
  7. To display images and videos try this:

    Intent intent = new Intent();
    intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 1);
    startActivityForResult(Intent.createChooser(intent,"Wybierz plik"), SELECT_FILE);

    ReplyDelete