Issues with the File function in Cordova/Phonegap impacting functionality

I am eagerly anticipating the day when the file function in Cordova finally starts working for me!

This particular section of code functions perfectly on Chrome (hooray!), but unfortunately not within the Android app:

function errorHandler(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 = 'Unknown Error';
      break;
  };

  alert('Error: ' + msg);
}





function InitFs() {
    if ( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/android/i) ) {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 10*1024*1024, afterInitFs, errorHandler);
    } else {
        window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
        window.LocalFileSystem = window.LocalFileSystem || {PERSISTENT: window.PERSISTENT};
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 10*1024*1024, afterInitFs, errorHandler);
    }
}
function afterInitFs(fs) {
     console.log('Opened file system: ' + fs.name);

  fs.sdcard.getFile('test.txt', {create: true, exclusive: false}, function(fileEntry) {
    fileEntry.createWriter(function(fileWriter) {
      fileWriter.onwriteend = function(e) {
        console.log('Write completed.');
      };
      fileWriter.onerror = function(e) {
        console.log('Write failed: ' + e.toString());
      };
      var blob = new Blob(['lol'], {type: 'text/plain'});
      fileWriter.write(blob);
     console.log(fileEntry.isFile + ' / ' + fileEntry.toURL());
    }, errorHandler);
  }, errorHandler);

}
InitFs();

(For Android, I have added initFs to the deviceready event and replaced "sdcard" with "root" for Chrome.)

So, the question that has been on my mind for the past two weeks is: What could be wrong with my code using the Cordova file API?

Answer №1

Here's a solution that worked for me personally:

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
    fileSystem.root.getDirectory("DO_NOT_DELETE", 
        {create: true, exclusive: false}, 
        gotDirEntry, 
        fail);
}
function gotDirEntry(dirEntry) {
    dir = dirEntry;
    dirEntry.getFile("sample.json", 
        {create: false, exclusive: false}, 
        readSuccess, 
        fileDoesNotExist);
}
function fileDoesNotExist(dirEntry) {
    dir.getFile("sample.json", 
        {create: true, exclusive: false}, 
        gotFileEntry, 
        fail);
}
function gotFileEntry(fileEntryWrite) {
    fileEntryWrite.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
    writer.onerror = function(evt) {
    };
    writer.write(localData);
    writer.onwriteend = function(evt) {
        dir.getFile("sample.json", 
            {create: false, exclusive: false}, 
            readSuccess, 
            fail);
    };
}
function readSuccess(fileE) {
    fileE.file(readAsText, fail);
}
function fail(error) {
    console.log("fail");
}
function readAsText(readerDummy) {
    var reader = new FileReader();

    reader.onloadstart = function(evt) {};
    reader.onprogress = function(evt) {};
    reader.onerror = function(evt) {};

    reader.onloadend = function(evt) {
        console.log("read success");
    };
    reader.readAsText(readerDummy);
}

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

Identifying clicks on various indices within a common class or element

My website has a navigation menu with unordered list items in it. <nav> <ul> <li id="zero"></li> <li id="one"></li> <li id="two"></li> </ul> </nav> I am working on implementing J ...

JavaScript: Selecting parent elements using getElementsByClassName

I am dealing with the following HTML code: <div class="item"> <img class="item-image" src="${item.getImage()}"/> <p>${item.getName()}</p> </div> and JavaScript: var classname = document.getElementsByClassName("item" ...

Ensure that Bootstrap 5.2 tooltips do not close when the cursor returns to the triggering element

TLDR: The tooltip flickers when moving the cursor from the tooltip back to the triggering element. I want the tooltips to open on hover and be clickable. I found a solution that works on Stack Overflow here. When you hover over an element, a tooltip appe ...

After renaming the package, the com.google.android.gms.R$styleable could not be located

Initially, my app was functioning smoothly and the Google Map feature was also operational. However, I decided to change the package name from "com.example.helloworld" to something more suitable for the Play Store. Following this, I made adjustments in the ...

Tips for using NodeJS with a MySQL database

Hello everyone, I'm new to this community so please bear with me if my question seems too simplistic. I've been tasked with a basic web project for one of my courses and will be using NodeJS+MySQL along with VS Code which has caught my eye. Howe ...

Ways to personalize Angular's toaster notifications

I am currently utilizing angular-file-upload for batch file uploads, where I match file names to properties in a database. The structure of the files should follow this format: 01-1998 VRF RD678.pdf VRF represents the pipeline name RD represents the lo ...

Displaying text on hover and showing a text box when a link is clicked using CSS and JavaScript

Hovering over the text will display "Edit," and clicking on it will reveal a text box. This function will be used to update content using ajax. HTML: <table> <thead> <tr> <th> Name </th> <th> Age </th> ...

Deciding whether to use Device WebView Kit or HTML for your project is

I am a bit confused about creating a website for mobile devices. If I have a specific webpage in mind that I want to target towards mobile devices, do I need to use the native webview kits provided by iOS, or can I simply code in HTML, PHP, Javascript, an ...

Avoiding GSON from processing elements that have an incorrect data type

Utilizing Retrofit along with OkHttp and GSON to interact with an online webservice. The webservice encompasses a default wrapper around all responses, structured as follows: { "resultCode":"OK", "resultObj":"Can be a string or JSON object / array", ...

How should callbacks be established for communication between a React app and an iframe using postMessage?

I'm encountering an issue with my website's communication with a third-party iframe. The site has three methods - login, sign, and get information - all functioning in a similar manner. I embed the third-party iframe and send a message to it usin ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

"Enhance your website with interactive jQuery lightbox buttons for easy navigation

As I explore the jquery lightbox plugin, I find it to be quite straightforward. However, I am curious if there is a way to make the "previous" and "next" buttons of the plugin function without the images needing to be named sequentially (e.g., "image1.jpg, ...

Image caption dynamically updated to match thumbnail caption using jQuery upon click event

My goal is to dynamically load the data-caption of thumbnail images when clicked, and then update the main image's data-caption when the main image is changed with a thumb image. I am currently struggling to make the data-caption update along with the ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

Guide to implementing Jest global Setup and Teardown in a Node.js application

I have integrated Jest tests into my Node.js project, with each test suite containing a beforeAll method that sets up a new test server and connects to a MongoDB database, and an afterAll method that shuts down the server and disconnects from the database. ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

How can I execute a different seed file using Sequelize-cli before running the main seed file?

I recently created a seeder file using sequelize-cli to bulk insert data into a MySQL database, and everything is working perfectly. However, one of the fields I am inserting (userId) requires a value that is already present in another table called User. ...

Transferring a JSON array from one activity to another using intents

I had a similar question before, but the solution didn't work for me. So I decided to ask again. My issue is with passing a JSONarray from one activity to another using an intent. In my code, I connect to a MySQL database and retrieve user data whic ...

Unable to start React Native CLI Project Initialization

I recently started using React Native CLI for my CRUD project. After initializing the project and running 'npx react-native run-android' inside the project folder, I encountered the following errors: npx react-native run-android info Starting JS ...