Issue with Cordova file plugin's inability to write to file

Currently tackling an issue with the Cordova file plugin (version 3.4.1) on Android. Despite combing through documentation, including the HTML5 file storage API and numerous StackOverflow posts (most of which suggest installing the plugin first - already done), I'm unable to find a solution for my specific problem.

Developing an app for Android, with plans for iOS integration later on, that successfully receives push notifications. However, I need to incorporate a feature allowing users to disable these notifications. Since there is no SharedPreferences plugin available yet, I've opted to write user preferences to a file on the device instead of querying the server constantly.

Following this tutorial () along with Cordova's guidelines, here is the code snippet used to interact with the file system:

var FileIO = {
    initializeFileSystem: function() {
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, FileIO.gotFS, FileIO.errorHandler);
    },

    gotFS : function(fileSystem) {
        console.log("FILE SYSTEM IS ", fileSystem.name);

        gFileSystem = fileSystem;
        FileIO.getFile({create : true}, FileIO.writeFile);
    },

    getFile : function(params, success) {
        gFileSystem.root.getFile('notification_preferences.txt', params, success, FileIO.errorHandler);
    },

    writeFile : function(fileEntry) {
        console.log(fileEntry);
        console.log('FILE URL: ' + fileEntry.toUrl());
        fileEntry.createWriter(function(fileWriter) {
            var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
            fileWriter.write(blob);
        }, errorCallback);
    },

    readFile : function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onloadend = function (e) {
                console.log('CONTENTS OF FILE: ', e.target.result)
            };
            reader.readAsText(file, 'text/plain');
        }, errorCallback);
    },

    removeFile : function(fileEntry){
        fileEntry.remove();
    },

// simple error handler
    errorHandler : function(e) {
        var msg = '';
        switch (e.code) {
            case FileError.QUOTA_EXCEEDED_ERR:
                msg = 'QUOTA_EXCEEDED_ERR';
                break;
            case FileError.NOT_FOUND_ERR:
                msg = 'NOT_FOUND_ERR';
                break;
            case FileError.SECURITY_ERR:
                msg = 'SECURITY_ERR';
                break;
            case FileError.INVALID_MODIFICATION_ERR:
                msg = 'INVALID_MODIFICATION_ERR';
                break;
            case FileError.INVALID_STATE_ERR:
                msg = 'INVALID_STATE_ERR';
                break;
            default:
                msg = e.code;
                break;
        }
        console.log('Error: ' + msg);
    }
};

Encountering an error when attempting to write to the file, shown below:

D/CordovaLog( 2871): file:///android_asset/www/cordova.js: Line 1034 : processMessage failed: 
Message: S01 File30696438 {"fullPath":"\/\/notification_preferences.txt","filesystemName":"temporary",
"isDirectory":false,"nativeURL":"file:\/\/\/data\/data\/org.changefactor.pgdemo\/cache\/notification_preferences.txt",
"filesystem":0,"isFile":true,"name":"notification_preferences.txt"}

Frustrated by this hurdle, unsure of what's going wrong or if there's a simpler way to store this data. Could the configuration be causing issues?

Answer №1

Using localStorage is ideal for storing user preferences, especially if you don't plan on accumulating a massive amount of data exceeding 5MB.

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

retrieving a date from a different source and displaying it in a date

Is there a way to ensure that the date format in an input of type date always follows the dd/MM/yyyy Brazilian pattern, regardless of the computer or browser specifications? <div class="input-group input-group text-center in ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

What steps can I take to improve the efficiency of this filtering process in Vue.js?

I am seeking ways to enhance the method I utilize for determining which values should be displayed in a table. At present, my table displays various values and is accompanied by input fields. The values chosen in these input fields serve as filters for the ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Discovering the Week by week commencement and conclusion dates utilizing angularjs

Previously, I was utilizing the angularjs-DatePicker from npm. With this plugin, I could easily select a date from the calendar. However, now I require two fields - FromDate and ToDate - to display the week StartDate and EndDate whenever a date within that ...

Is there a way to use Knex to transform the relevant rows of a joined table into a nested object structure?

How can I retrieve a user's relevant row from the users table using knex, along with an array of all the groups associated with a user whose id is 1? Here is the structure of my users table: https://i.sstatic.net/9lhPZ.png This is the setup of my gr ...

What is the best way to activate Google Maps API functions with the gMap jQuery plugin?

Is there a way to call the native Google Map API's "resize" method after initializing the gMap plugin for jQuery? According to the documentation, I am setting up my map element like this: var defaults = { latitude: 0, longitude: 0, zoom: ...

Creating a dynamic image gallery in Handlebars using Express

I have successfully implemented handlebars with puppeteer to generate a PDF server-side and save it in my database. However, I am facing an issue with loading images stored in an assets directory through the img tag. In my index.js file, I have a helper c ...

The inclusion of JavaScript code in the WPF WebBrowser Control does not support the use of the Object.freeze

When integrating JavaScript code into a WebBrowser Control in my WPF App, I encountered an issue with the function Object.freeze(), resulting in an error when running the application. Here is how my .xaml file with the WebBrowser control looks: <Windo ...

JavaScript Deviance

I am facing an issue with my JS code while trying to send form data to a .php file via AJAX. The problem occurs when the input fields are filled - for some reason, my client-side page refreshes and the php file does not get executed. However, everything wo ...

The content within Contentful is presented in a JSON object format, but accessing specific values is proving to be

I have successfully added two records in the contentful database and now I am attempting to fetch the content from Contentful into my React-hooks website. However, I am facing difficulties retrieving the values for title, description, image, and shortDescr ...

What are some ways to access my AsyncStorage data from any location?

I am utilizing the saga library and storing tokens in AsyncStorage. My goal is to be able to freely access the token retrieved from AsyncStorage in both the loadUserPosts function and the loadPosts function. Where should I add async and how can I correct ...

What steps can I take to ensure that WebStorm properly recognizes a package's functions?

No matter what I do, WebStorm refuses to stop throwing inspection warnings when I try to use the JOI package in my node.js project. The code runs fine and there are no runtime errors, but the warning persists. I have updated the package, explicitly install ...

Creating a dynamic circle that expands in size based on the duration the user presses down (using Java Script)

I have a fun challenge for you! I want to create a growing circle on a canvas based on how long you hold your mouse button. Currently, I can draw a fixed width circle where my mouse was when I clicked, but I need it to dynamically change size as you hold t ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Controller not being reached by Ajax request

Hi, I am currently attempting to utilize Ajax with Spring Mvc Portlet in Liferay. I have a JSP file and Controller Class set up. My goal is to insert data into a form, but for some reason, my controller class is not being called when I click the submit but ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

Obtain the value of a two-handle slider using jQuery

Here is the HTML and JS setup I have for implementing a jQuery two-handle range slider: .html <p> <input class="amount" readonly style="border:0; color:black; background: transparent; text-align: center;" type="text"> </p> <div cla ...

What is the best way to trigger an API call using AJAX whenever the page loads and at regular intervals using `setInterval()` function?

New to coding and seeking guidance: I have a basic AJAX feature in my project that triggers a GET API request every 3 seconds: <script> $(document).ready( function() { setInterval(function() { $.get(&apos ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...