Add Image To Gallery Android Studio | Image Not Showing In Gallery

How to add photo to gallery programmatically ? If you want to learn the java code for above task then you are at right place. But first, let’s see your problem so that you can decide to continue or not.


add image to gallery
You are making a Android software that is related to image editing. Now you are successful in saving output inage file to storage. But when you want to see that image in gallery then it won’t show up.

Now, if you have similar problem then go ahead, follow our tutorial that will help you. Now let’s start coding.

Please keep this thing in mind that below codes are written in Java and not kotlin. We will update with kotlin soon

Step 1 : Declare a string for your path of image.

 String imagePath = "/sdcard/myimage.png"; // Put your image path here. 

Step 2: Create a Intent object as given below


Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

Step 3: Now make Uri from your image path.


Uri contentUri = Uri.parse(imagePath);

Step 4: Now set data to intent and then send broadcast as given below.


intent.setData(contentUri);
this.sendBroadcast(intent);

And thats it, now your image will be appear in gallery.

If you want full method for adding image to gallery in Android then here it is.

Final Codes:

If you have Uri of image

private void addToGalleryFromPath(String imagePath) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

Uri imageUri = Uri.parse(imagePath);
intent.setData(imageUri);
this.sendBroadcast(intent);
}

If you have File of image

private void addToGalleryFromFile(File imageFile) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

Uri imageUri = Uri.fromFile(imageFile);

intent.setData(imageUri);
this.sendBroadcast(intent);
}

If you have Uri of image

private void addToGalleryFromUri(Uri imageUri) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(imageUri);
this.sendBroadcast(intent);
}

Now you can easily show your image to gallery. This problem is a very common problem that beginner programer can not understand. There are some small coding that are easy but confusion.

Note
1) Please import the libraries as required.
2) We are using Uri in above method not URI. Uri can be imported as android.net.Uri .
3) Make sure you have permission to read and write external storage.

Leave a Reply

Your email address will not be published. Required fields are marked *