Output:
1/ Modify your activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imgGallary"
android:layout_width="400dp"
android:layout_height="400dp"
android:scaleType="fitXY"/>
<Button
android:id="@+id/btnGallary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:text="Open Gallary"/>
</LinearLayout>
2/Modify your MainActivity.java .
package com.tutorialb.getpicturefromfolder;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private final int Gallary_REQ_CODE = 100;
ImageView IMG_gallary;
Button BTN_gallary;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
IMG_gallary = findViewById(R.id.imgGallary);
BTN_gallary = findViewById(R.id.btnGallary);
BTN_gallary.setOnClickListener(new View.OnClickListener() {
@SuppressLint("QueryPermissionsNeeded")
@Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto,Gallary_REQ_CODE );
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
if (requestCode==Gallary_REQ_CODE){
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
IMG_gallary.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}