Unable to write data to JSON file using ngcordova file plug in


#1

hi, below are the portion of the html code

<label class="item">
                <span class="input-label">First Name</span>
                <input type="text" placeholder="First Name" value="{{quote.Quot_Cust.Cust_Fname}}">
            </label>
            <label class="item">
                <span class="input-label">Last Name</span>
                <input type="text" placeholder="Last Name" value="{{quote.Quot_Cust.Cust_Lname}}">
            </label>
            <label class="item">
                <span class="input-label">Email</span>
                <input type="email" placeholder="Email" value="{{quote.Quot_Cust.Cust_Email}}">
            </label>
            <label class="item">
                <span class="input-label">Phone</span>
                <input type="number" placeholder="Phone" value="{{quote.Quot_Cust.Cust_Mob}}">
            </label>
            <label class="item">
                <span class="input-label">Date Of Birth</span>
                <input type="date" placeholder="DOB" value="{{quote.Quot_Cust.Cust_Dob}}">
            </label>
<button ng-click="saveQuote(quote)">save</button>

and the following is potion of my JS file.

$scope.saveQuote=function(quote){
	 $cordovaFile.writeExistingFile('/data/', "cust_dtls.json", JSON.stringify(quote))
      .then(function (success) {
        console.log(JSON.stringify(quote))
      }, function (error) {
        console.log(error)
      });
	}
})

i have installed the plug and I have included ngCordova js file.

Please to let me know where i have been making mistakes.

Thanks


#2

I think your problem is with that you are trying to write to an absolute path /data/.

There are commands for figuring out data locations on the SD card. I think it is something like cordova.file.dataDirectory.

In either scenario, share your logs so we can figure out what exactly isn’t working.

Regards,


#3

Sorry for the late reply. got held up.

yeah i changed my method to

$scope.saveQuote=function(){
	 $cordovaFile.createFile(cordova.file.externalApplicationStorageDirectory, "newfile.txt",true)
      .then(function (success) {
        console.log("success the file has been created")
      }, function (error) {
        console.log("error"+error)
      });
	}`

Just to see whether it creates a file.

This is my log.

1 398478 error Error: Failed to execute ‘send’ on ‘XMLHttpRequest’: Fai
led to load ‘file:///android_asset/www/data/Quot_Dtls.json’.
at Error (native)
at http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:17607:11
at sendReq (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:17408:9)
at $http.serverRequest (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.j
s:17126:16)
at processQueue (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:20962
:27)
at http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:20978:27
at Scope.$eval (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:22178:
28)
at Scope.$digest (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:2199
4:31)
at Scope.$apply (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:22282
:24)
at done (http://192.168.1.29:8100/lib/ionic/js/ionic.bundle.js:17439:47)
2 421785 log error[object Object]

when i dont log i am able to open the Quot_DTls.json file through the app. as it displays all the things i want from the file. but when i start logging it dosent happen.

and coming to $cordovaFile. when i call the savequote method the last line of the log.

If you could give me an example on how to use it correctly i would be glad thanks.


#4

For a starters do console.log(JSON.stringify(error)) to get more meaningful error


#5

Did that. error code 5. Its an encoding error


#6

Maybe this will help? http://stackoverflow.com/questions/26858982/cordova-ionic-ngcordova-ios-or-iphone-file-read-error-code-5-encoding-err/27523006#27523006


#7

hi, thanks for helping me write data to json. but sorry again i have a stupid question hope. you help me out with it. when append the json files how do it append them inside an array

for example
when i use file write this is how it writes to the file.

{"name":"abc"}{"name":"bcd"}

but that is not valid json format. i want it to be

[{"name":"abc"},{"name":"bcd"}]

can you help please.


#8

Can you show me your code where you write to JSON?


#9

This is how i write to a file.

$scope.saveQuote=function(quote){

		var data = JSON.stringify(quote);
	 $cordovaFile.writeFile('user.json',JSON.stringify(quote),{append:true})
      .then(function (success) {
        console.log("success the file has been created")
      }, function (error) {
        console.log("error"+JSON.stringify(error))
      });
	$scope.refreshQuotes();
	}

This is how i read from the file.

$cordovaFile.readAsText('user.json')
			.then(function (success) {
				$scope.quotes = JSON.parse(success);
				console.log("Successful in reading the file initially:"+JSON.parse(success));
			}, function (error) {
				console.log("error reading the file"+JSON.stringify(error))
					});

#10

Well before writing to file you will need to Read file first, JSON.Parse it’s content, then check if it is empty, If it is empty then create new array and push your user object to i, then save that array to file. If it is not empty, then push to existing array and JSON.stringify before saving.


#11

ok thanks. will try doint that. :slight_smile:


#12

@yurinondual i have another doubt. when i close the app and remove it. the array losses its data right.

so i have to read the file and store the contents of the file to an array and then add my object to it right?

but then this is how my array json file looks now

[{name:abd},[{name:bcd}]]

could you please help.

Thanks…


#13

@venkyangara Were you able to write to json file stored in your phone device? I always get the encoding error (error code 5). I tried with JSON.stringify() as well, but still get the same error. Can you help mw with this?

Thanks in advance


#14

For those who are looking for a way to write to json file located in the phone device

     function writeToFile(fileEntry, dataObj) {
        fileEntry.createWriter(function (fileWriter) {

            fileWriter.onwriteend = function() {
                // successfully written to the file
            };

            fileWriter.onerror = function (e) {
                 // error writing to the file
            };

            fileWriter.write(dataObj);
        });
    };

The Value passed to writeToFile function must be an object. You can use window.resolveLocalFileSystemURL to create the fileEntry object and then pass both the fileEntry object and the data to be written to the writeToFile function

Tip: As you can see, ngCordova is not used in this function. Its always better to check once without ngCordova implementation when your code doesn’t work.