Adding Cordova APIs to Android via CLI: File API


In this article, we are in part 4 of exploring the Cordova APIs, which started in https://iphonedevlog.wordpress.com/2014/01/31/adding-cordova-apis-to-android-via-cli-accelerometer-and-camera/ Refer to that article to set up your Cordova PhoneGap project files. You’ll want to follow the “Set Up the Android Project” section through step 9 inclusive. On this page, we’ll explore the File API from the perspective of getting our feet wet.

You can continue the code by copying/pasting from this page into that project’s index.html page, or start a new page and link to it via a button on that page to access it (which is what I did). If you are starting a new page, copy/paste this HTML skeleton into a file.html page to follow along:

<!-- ********************* HMTL5 Skeleton begin *********************** -->
<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <meta name="format-detection" content="telephone=no" />
 <!-- WARNING from Cordova: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
 <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Cordova APIs</title>
<style type="text/css">
 input[type="text"] { 
 border-radius:8px; background-color:#eee;
 border:#878787 solid 1px; padding:0 1em;margin:.5em;
 height: 45px;
 font-family: "Helvetica"; color: #000; font-size:1em; text-align:center;
 -webkit-appearance:none;
 }
 .buttonClass {
 border-radius:8px; background-color:#eee;
 border:#878787 solid 1px; padding:0 1em;margin:.5em;
 height: 45px;
 font-family: "Helvetica"; color: #000; font-size:1em; text-align:center;
 -webkit-appearance:none;
 } 
 .segment {
 display:block; border-radius:8px; background-color:#eee;
 border:#878787 solid 1px; padding:1em; margin:.5em;
 font-family: "Helvetica"; color: #000; font-size:1.3em; text-align:left;
 -webkit-appearance:none; 
 }
 </style>
 <script type="text/javascript" src="cordova.js"></script> 
</head> 
<body> 
</body> 
</html> 
<!-- ********************* HMTL5 Skeleton end *********************** -->

File Write

File API is an application programming interface (API) to read, write, and navigate file system hierarchies, based on the w3c file api. We’ll follow this page from the docs to set it up: http://docs.phonegap.com/en/3.3.0/cordova_file_file.md.html#File Please review the page to gain an understanding of the steps we’ll be following.

We will programmatically create a text file in the device’s root directory, allow the user to write in it, then display its contents on the same HTML page. We’ll also provide a button to overwrite the contents to clear it.

We’ll be trying out the methods:

seek: Moves the file pointer to the specified byte.

truncate: Shortens the file to the specified length.

write: Writes data to the file.

1. Set the project’s directory in Terminal (type cd in the terminal, drag the folder to the terminal, click on the terminal to select it, hit Enter) and download the plugin:

cordova plugin add org.apache.cordova.file

2. Add the file-transfer plug-in:

cordova plugin add org.apache.cordova.file-transfer

3. Make sure they are available:

cordova plugin ls

4. Add to config.xml:

<feature name="File">
 <param name="android-package" value="org.apache.cordova.file.FileUtils" />
</feature>
<feature name="FileTransfer">
 <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />
</feature>

5. Make sure this is in AndroidManifest.xml; if not, add it:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

6. Add the following to just above the </body> tag:

<!-- ********************* Write File begin *********************** -->
<div class="segment">
 <h2>Write File</h2>
 <p>When this page was loaded, it automatically created a CordovaAPI.txt file in the root directory of the device.</p>
<p>Add your own words to the file:</p>
<form id="myForm" name="myForm2">
<input type="text" id="userInput" name="userInput2">
<input type="button" class="buttonClass" value="Submit" onclick="writeToFile()">
</form>
<input type="button" class="buttonClass" onclick="deleteContents()" value="Delete the file contents">
<br><br>
 <input type="button" class="buttonClass" onclick='window.location="https://iphonedevlog.wordpress.com/2014/02/21/adding-cordova-apis-to-android-via-cli-file-api/"' value="View Code on iPhoneDevLog">
</div>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
 document.addEventListener("deviceready", onDeviceReady, false);
 // device APIs are available

 function onDeviceReady() {
 }

 function writeToFile() {
 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
 }
// put this file in the root of the device's file system
 function gotFS(fileSystem) {
 fileSystem.root.getFile("CordovaAPI.txt", {create: true, exclusive: false}, gotFileEntry, fail);
 }
function gotFileEntry(fileEntry) {
 fileEntry.createWriter(gotFileWriter, fail);
 }

function gotFileWriter(writer) {
 var form = document.getElementById('myForm'); // get the form
 var userText = form.userInput.value; // get the text field value
 writer.seek(writer.length); // get the length of the file; go to end
 writer.write('\n\n' + userText); // skip a space and start writing
 writer.onwriteend = function(evt){
 alert("You wrote ' " + userText + " ' at the end of the file.");
 } 
 form.userInput2.value = "";
 readTheFile(); // show new file contents
}
// ******* delete the file contents **********
function deleteContents() {
 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS3, fail);
 }
// get this file in the root of the device's file system
 function gotFS3(fileSystem) {
 fileSystem.root.getFile("CordovaAPI.txt", {create: false, exclusive: false}, gotFileEntry3, fail);
 }
function gotFileEntry3(fileEntry) {
 fileEntry.createWriter(gotFileWriter3, fail);
 }

function gotFileWriter3(writer) {
 writer.onwriteend = function(evt) {
 writer.truncate(writer.length); // truncate entire file
 writer.onwriteend = function(evt) {
 writer.seek(0); // start at beginning of file
 writer.write(""); // add no content
 writer.onwriteend = function(evt){
 alert("You deleted the file contents.");
 }
 readTheFile(); // show file contents
 };
 };
 writer.write(""); 
 }
function fail(error) {
 console.log(error.code);
 }
</script>
<!-- ********************* Write File end *********************** -->

The above steps are used to write a file to the root directory of the device, with a button provided to delete the contents of the file. Now follow the next steps to read the file, displaying the contents onscreen.

File Read

In this step, we’ll display the above CordovaAPI.txt contents on the page.

We’ll be trying out the methods:

readAsDataURL: Read file and return data as a base64-encoded data URL. Display it onscreen through innerHTML.

readAsText: Reads text file. Display it onscreen through innerHTML.

Steps 1-5 above already added the File API and other entries needed for the read functions.

1. Continuing from the steps above, add the following to just above the </body> tag:

<!-- ********************* Read File begin *********************** -->
<div class="segment">
 <h2>Read File</h2>
 <p style="font-style:italic;">The contents of the above file in two different versions, as data URL and data text:</p>
 <div class="segment">
 <p id="data1"></p>
 <br>
 <p id="data2"></p>
 </div>
 <p>You can hold a finger over the above contents and choose to copy it or share via email, according to the options on your device.</p>
 <p>Now exit this app, open a file reading program, navigate to the root of the device, and scroll to the CordovaAPI.txt file. Open to read it. 
</p>
<br><br>
 <input type="button" class="buttonClass" onclick='window.location="https://iphonedevlog.wordpress.com/2014/02/21/adding-cordova-apis-to-android-via-cli-file-api/"' value="View Code on iPhoneDevLog">
</div>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
 document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
 function onDeviceReady() {
 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS2, fail);
 }

function readTheFile() {
 window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS2, fail);
 }

 function gotFS2(fileSystem) {
 fileSystem.root.getFile("CordovaAPI.txt", null, gotFileEntry2, fail);
 }
function gotFileEntry2(fileEntry) {
 fileEntry.file(gotFile2, fail);
 }
function gotFile2(file){
 readDataUrl(file);
 readAsText(file);
 }

// puts the txt contents on the page as data URL
 function readDataUrl(file) {
 var reader = new FileReader();
 reader.onloadend = function(evt) {
 var element = document.getElementById('data1');
 element.innerHTML = '<strong>Read as data URL:</strong> <br><pre>' + evt.target.result + '</pre>';
 };
 reader.readAsDataURL(file);
 }
// puts the txt contents on the page as data text
 function readAsText(file) {
 var reader = new FileReader();
 reader.onloadend = function(evt) {
 var element = document.getElementById('data2');
 element.innerHTML = '<strong>Read as data text:</strong> <br><pre>' + evt.target.result + '</pre>';
 };
 reader.readAsText(file);
 }
function fail(error) {
 console.log(error.code);
 }
</script>
<!-- ********************* Read File end *********************** -->

2. Prepare the files in the terminal:

cordova prepare android

3. Compile the apk file:

cordova compile android

(If you watch the platforms/android/bin/ folder, you can see the files as they are removed and replaced.)

4. Locate the apk file at platforms/android/bin/CordovaAPI-debug.apk and put it on your device.

5. When the page opens, it creates a CordovaAPI.txt file in the root directory of the device. Add text to the text input box and Submit. Look lower to see the file data read back in two different formats. Close the app, open a file-reading app, and navigate the root directory to the CordovaAPI.txt file and open it.

file-write

file-read

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s