Issues with Phonegap (Cordova) preventing file writing on Android devices

I am encountering a frustrating problem with cordova when attempting to write files to Android devices.

Despite the logs showing that everything is functioning correctly and the plugin methods are returning successful responses, I cannot locate the files anywhere on the device.

Currently, I am using a fresh phonegap test application and followed a guide along with their code example exactly. The plugins are installed as per the logs and are running.

I expect the file to appear in /android/data/com.testapp.myapp/files

This is my testing code:

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, app.gotFS, app.fail);
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },

    gotFS: function(fileSystem) {
        fileSystem.root.getFile("testFile.txt", {create: true, exclusive: false}, app.gotFileEntry, app.fail);
    },

    gotFileEntry: function(fileEntry) {
        fileEntry.createWriter(app.gotFileWriter, app.fail);
    },

    gotFileWriter: function(writer) {
        writer.onwriteend = function(evt) {
            console.log("contents of file now 'some sample text'");
            writer.truncate(11);
            writer.onwriteend = function(evt) {
                console.log("contents of file now 'some sample'");
                writer.seek(4);
                writer.write(" different text");
                writer.onwriteend = function(evt){
                    console.log("contents of file now 'some different text'");
                }
            };
        };
        writer.write("some sample text");

    },

    fail: function() {
        alert("failed");
    }    
};

And here are the log entries from the logCat indicating that it's working:

09-26 07:24:37.991 I/chromium( 2027): [INFO:CONSOLE(49)] "Received   

Event: deviceready", source: file:///android_asset/www/js/index.js (49)
09-26 07:24:38.591 D/TEST    ( 2027): cdvfile://localhost/persistent/testFile.txt: 16
09-26 07:24:39.063 I/chromium( 2027): [INFO:CONSOLE(62)] "contents of file now 'some sample text'", source: file:///android_asset/www/js/index.js (62)
09-26 07:24:39.075 D/TEST    ( 2027): cdvfile://localhost/persistent/testFile.txt: 15
09-26 07:24:39.155 I/chromium( 2027): [INFO:CONSOLE(65)] "contents of file now 'some sample'", source: file:///android_asset/www/js/index.js (65)
09-26 07:24:39.363 I/chromium( 2027): [INFO:CONSOLE(69)] "contents of file now 'some different text'", source: file:///android_asset/www/js/index.js (69)

If anyone has insight into why this issue is occurring, I would appreciate any help.

Thank you!

Answer №1

Hey there, keep it simple! This code snippet is all about writing data to a file using the 'decdata' variable. Don't forget to update 'somefolder' with the correct folder in the root directory and 'datafilename' with the name of the file where the data is stored. Also, remember to include the file plugin.

function start(){
       window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, writedata, fail);
}
    var decdata;

 function writedata(fileSystem) {
        fileSystem.root.getDirectory("<<somefolder>>", { create: true }, gotDir);
    }


 function gotDir(dirEntry) {

        dirEntry.getFile(<<datafilename>>, { create: true, exclusive: false }, gotFile);
    }


function gotFile(fileEntry) {

        fileEntry.createWriter(gotFileWriter, fail);

    }

    function gotFileWriter(writer) {
        writer.onwriteend = function (evt) {
            writer.truncate(1);
            writer.onwriteend = function (evt) {
                writer.seek(0);
                writer.write(decdata);
                writer.onwriteend = function (evt) {

                }
            };
        };
        writer.write("some sample text");
    }
    function fail(error) {
        alert('error' + error.code);
    }

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

The error message "Type Error: val.toString is not a function - mysql npm" indicates

I'm encountering an issue with the 'mysql' package in NPM on a nodeJS backend and I'm puzzled by this error message: TypeError: val.toString is not a function at Object.escape (/Applications/MAMP/htdocs/nodeJS_livredor/node_modules/sql ...

Detect both single and double click events on a single Vue component with precision

I did some online research but couldn't find a clear answer. However, I came across this article -> Since I didn't quite understand the solution provided, I decided to come up with my own inspired by it. detectClick() { this.clickCount += ...

Creating a Query String in a web URL address using the state go method in Angular State Router

On my product list page, there is a list of products. When I click on a particular product, a function is called that uses state.go. Issue with dynamic functionality: $state.go('home.product.detail', { 'productID': "redminote4", &apo ...

Using Javascript to send key codes to an HTML <textarea> element

I'm having trouble figuring out how to initiate a keydown event on a textarea element. For example, I have two textarea elements and I want the second box to display whatever is typed in the first one. However, for some reason, I need to do this using ...

Introducing LightZAP v2.54 (silent update2), the revolutionary Lightbox custom plugin that seamlessly launches when the page loads using the designated tag name (#img1)

As I have the LightZAP plugin installed on my website as an alternative to Lightbox, I am looking to trigger it (to display an image gallery with a specific image) when the page loads using the following link: index.html#img1, if possible. I have come acr ...

Using JQuery to showcase JSON data

Struggling with showcasing nested objects from a JSON structure on a webpage using JQuery's .getJSON function. The code snippet with the JSON data is as follows: { "widget": { "debug": "on", "window": { "title": "Sample Konfabulator W ...

Enabling draggable functionality for divs using JSPlumb and a toggle button

http://jsfiddle.net/taoist/fsmX7/ The scenario presented in the code snippet above involves toggling the draggable state of the .textDivContainer element based on user interaction. The desired behavior is for the element to be non-draggable by default, an ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Retrieve a parameter from jQuery and pass it to a JavaScript function

Currently, I am working with Puppeteer and encountering an issue where the "selector" is undefined when calling this function. async function checkIfTextIsPresent(page, selector){ let myElement = await page.evaluate(() => document.querySelector(sel ...

"Resetting the React state within a React context is causing a re

I'm experiencing an issue where the state in my React context keeps resetting on every render. I was under the impression that this should not happen with React context and global states. Unfortunately, I am unsure of how to resolve this. Whenever I ...

rendering json data as html using javascript

I am encountering some difficulties with displaying JSON data in HTML using JavaScript. Here is the sample JSON data: { "80": { "Id": "80", "FirstName": "Ranjan", "MiddleName": "Kumar", "LastName": "Gupta", "Gender": "Male", "Locat ...

Getting started with the AngularJs plugin is the first step in building dynamic web applications. However, a common issue arises when the browser is

Exploring the world of AngularJS has been an interesting journey for me, as outlined in the title. I recently came across a useful drag and drop plug-in that I wanted to incorporate into my website. However, after downloading the code from GitHub, I faced ...

Which frameworks are categorised under Express-based frameworks?

Considering a job opportunity to develop a web app, one of the requirements is to "use node.js with an express based framework." My understanding is to use node.js with express.js, but what exactly does an express based framework entail? Does it refer to ...

Using Javascript to interact with a two-dimensional JSON array

Similar Question: I have a nested data structure / JSON, how can I access a specific value? While working with the US Census API, I encountered a two-dimensional JSON array after making a request using jQuery.get(). The result (data) resembles the fol ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

Bringing json files from a directory into mongoDB

My current challenge involves managing a directory structure that consists of multiple sub-directories, containing approximately one million JSON files. I am looking to import all of this data into mongoDB, but have been unable to locate any helpful tutori ...

Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend... public class ScoreModel { public string Subject { get; set; } public float Score { get; set; } ...

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

"Error occurred: Unable to execute bgColor as a function" on HTML select onchange event

I am having an issue with my HTML switch that has an onchange tag triggering the JavaScript function bgColor with the argument this. However, every time I attempt to use this, I receive an error message: Uncaught TypeError: bgColor is not a function. Can a ...

Updating the UI with AsyncTask

I have been researching AsyncTasks and how to update the UI after an AsyncTask has executed. For example, I have two Java files. File 1: MyFragment.java, File 2: MyAsyncTask.java In this scenario, I am executing MyAsyncTask on MyFragment. Once it has exe ...