22

I wanna to open phones gallery through a button click.
In my activity I have a button, I want to open the gallery through that button click.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Jyosna
  • 4,436
  • 13
  • 60
  • 93
  • dup: http://stackoverflow.com/questions/2169649/get-pick-an-image-from-androids-built-in-gallery-app-programmatically – samus Jul 07 '14 at 16:49

5 Answers5

45

Here is sample code for open gallery from app.

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

OnActivityResult for get image.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_IMAGE) {
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED)  {
            Toast.makeText(getActivity(), "Canceled", Toast.LENGTH_SHORT).show();
        }
    }
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
35

To bind your button click listener: (This should be in your onCreate method.)

ImageButton btn_choose_photo = (ImageButton) findViewById(R.id.add_photo_choose_photo); // Replace with id of your button.
btn_choose_photo.setOnClickListener(btnChoosePhotoPressed);

To open gallery: (This should be in your activity class.)

public OnClickListener btnChoosePhotoPressed = new OnClickListener() {      
    @Override
    public void onClick(View v) {
        Intent i = new Intent(Intent.ACTION_PICK,
                   android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        final int ACTIVITY_SELECT_IMAGE = 1234;
        startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 
    }
};

To get the chosen image: (This should be in your activity class.)

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

    switch(requestCode) { 
    case 1234:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
            /* Now you have choosen image in Bitmap format in object "yourSelectedImage". You can use it in way you want! */
        }
    }

};
necixy
  • 4,964
  • 5
  • 38
  • 54
  • thanks , was looking to select image from the device only and not from external apps – A.Alqadomi Nov 02 '17 at 10:11
  • Thanks @necixy for your answer. How can we change this code to open file manager instead of gallery, to choose *.xyz files !? – Omid1989 Feb 03 '18 at 06:57
11

On your button's OnClickListenner, create this intent :

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                  "content://media/internal/images/media"));

Does this fit with your expectations ?

Alexandre Nucera
  • 2,183
  • 2
  • 21
  • 34
  • It works pretty well with `startActivity(intent)` ... what should be next step, if we want to retrieve back selected photo. In other words how can we fire `startActivityForResult()` method. thanks! – Nikhil G Jan 09 '18 at 06:20
  • 1
    I have no idea, I haven't touch Android in years and the SDK has probably changed a lot since – Alexandre Nucera Jan 09 '18 at 12:31
5

Try this example, it worked for me to open my gallery by clicking a Button I am sure this will work for you

public class MainActivity extends Activity {

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;

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

        img = (ImageView)findViewById(R.id.imageView1);

        ((Button) findViewById(R.id.button1))
                .setOnClickListener(new OnClickListener() {
                    public void onClick(View arg0) {
                        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);
                System.out.println("Image Path : " + selectedImagePath);
                img.setImageURI(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);
    }
}

and here is your main.xml should be looks like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

Also in MainActivity.java, add all these imports

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

Apply this example and you are done :)

Zubair Ahmed
  • 2,857
  • 2
  • 27
  • 47
0

UPDATE:

according to documentation activityForResult is deprecated starting from api level 30

enter image description here

You have to use registerForActivityResult

 private lateinit var launcher: ActivityResultLauncher<String>
   ...
 // NOTE YOU SHOULD REGISTER IN `onAttach ()` or IN `onCreate()` callbacks.
 override fun onAttach(context: Context) {
    super.onAttach(context)
   ...

    launcher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        //.. your picked image result here
    }

Then call it like:

 launcher.launch("image/*")
Narek Hayrapetyan
  • 1,731
  • 15
  • 27