Pictures are not showing up in the gallery after they have been saved

 if (action.equals("saveToGallery")) {

                        JSONObject obj = args.getJSONObject(0);
                        String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null;
                        String imageName = obj.has("imageName") ? obj.getString("imageName") : null;
                        String savedImgSrc = saveImageToGallery(imageSource, imageName);
                        Log.v("SAve To Gallery ", "saved file url:  " + savedImgSrc);

                        return new PluginResult(PluginResult.Status.OK);
                    }
                    return new PluginResult(PluginResult.Status.INVALID_ACTION);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
                }

public String saveImageToGallery(String imgSrc, String imgName) {
        Log.v("Save To Images Folder", "image Source:  " + imgSrc + " , Image Name:" + imgName);

        Context context= this.context;
        AssetManager assetManager = context.getAssets();
        File directory = new File("/sdcard/AppImages/");
        directory.mkdirs();
        File imageFile = new File(directory, imgName);
        
        try {
            InputStream inputStream = null;
            inputStream = assetManager.open("www/" + imgSrc);
            OutputStream outputStream = new FileOutputStream(imageFile);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            outputStream.write(data);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            inputStream.close();
            outputStream.close();
        } 
        catch (IOException exception) {
            Log.w("ExternalStorage", "Error writing " + imageFile, exception);
        }
        return imageFile.getAbsolutePath();

    }

I have implemented the above code to save images to the device gallery. However, there seems to be a delay in displaying the image immediately after saving it. It only appears when I reload the application or the gallery after some time. Any suggestions on how to fix this issue would be greatly appreciated.

Answer №1

Give this a shot:

If you've just uploaded your image to the gallery, make sure to broadcast

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+
 Environment.getExternalStorageDirectory())));

Crossing my fingers that it does the trick for you. :)

Answer №2

Ensure your media is scanned manually after saving the image using the following code snippet:

// Notify the media scanner about the new file to make it
// immediately accessible to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the original AndroidManifest.xml necessary when modifying system apps?

When it comes to editing a system APK, there are several key steps to follow: Begin by creating a backup of the original APK. Next, decompile the working APK. Make necessary changes to the code or files. Recompile the modified APK. Lastly, copy and paste ...

generate a series of nested divs within one another

I am looking to create a custom nested loop that will generate div elements based on the content of my h1 and h2/h3 tags. I understand this may have been covered in other inquiries, so any guidance would be appreciated :) Here is the initial HTML: <h1& ...

Tips for configuring options within a jQuery widget factory using data retrieved from server-side variables stored in a JSON file

I am looking to configure the settings for a widget using JSON file variable values. How can I achieve this and how do I transfer the JSON file to the client side? The following code snippet is taken from the jQueryUI Widget Factory <script> $(f ...

Selecting a range with regular expressions

I'm having trouble extracting a specific key-value pair from a JSON document using regular expressions. I'm finding it hard to figure out how to narrow down the selection of the matching data. Currently, when using the following regex, "email"& ...

interactive vuetify navigation trail elements

Currently working on a vuetify project and I'm facing an issue with implementing breadcrumbs. The problem arises when clicking on a breadcrumb, as it deletes the ones that come after it in the list. I've tried some code snippets but could only ma ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Arrange the array depending on the existence of properties in the objects

Is there a way to efficiently organize an array like the following in cases where certain fields are missing? For instance, consider the current array: const users = [ { id: 1, firstname: 'Jerry' }, { id: 2, firstname: & ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

Cookies set by ExpressJS Cookie-Parser do not remain across multiple HTTP requests

Currently, I'm utilizing Cookie - Parser in conjunction with express.js. Within my express config file, I have included app.use(cookieParser()). In the main (app.js) file for the server, I am setting the cookie whenever there's a POST request to ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Why does JSON remain unchanged when a value is explicitly assigned in Javascript

Why isn't my JSON structure updating when I explicitly assign a new value? items[0][i]['human_addressItem'] = address; I am trying to reverse geocode the latitude and longitude to obtain the human address, which is working fine. However, I ...

What is the most effective way to use Javascript to update an image depending on the selected value in a dropdown

My JavaScript skills are limited, but I have successfully created a form with 4 drop-down selection boxes on the left side for users to choose from (State, Car, Year, Condition). After making their selections, users can click a 'calculate' butto ...

Debugging Slideshows Using JavaScript

I am currently working on creating a slideshow and I'm facing some challenges with the JavaScript functionality. Everything seems to be running smoothly except for one issue - when I click right once, it transitions correctly, but if I then click left ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

Vanilla JavaScript Troubleshooting: Top Scroll Button Issue

Attempting to develop a Scroll To Top Button utilizing Vanilla JS, encountering errors in the dev console. Existing jQuery code that needs conversion to vanilla js Uncaught TypeError: Cannot read property 'addEventListener' of null My Vanilla ...

How can I extract the minimum price from this array list using Reactjs?

In my ReactJS project, I have an array list structured like this. I am trying to find the minimum price from this list. For example, if 'totalll' is 100, how can I achieve that? Please advise on how to navigate through the array to retrieve the i ...