Combining native app with worklight project - android

I am working on a worklight application which needs file IO in it. I have written that code in an android project separately. Can anyone tell me how I can combine the both of them into one?

Like Idan said, there's no way to port your existing native application to a Worklight Hybrid Application. However, you can take advantage of the File API that works out of the box with Worklight Hybrid Applications in different environments, such as Android and iOS. If you create a Cordova Plugin you will need to create a plugin for all the environments you wish to support.
Here's a quick example of the File I/O API for Writing a file:
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(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");
}
function fail(error) {
console.log(error.code);
}
Here's an example of Reading a file:
// Wait for Cordova to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}

There is no way to combine an existing Worklight Hybrid application with an existing Native application. The correct approach for a Worklight application would be to write a Cordova plug-in to do what you want on the native side of things.
Please see these training modules which explain how to do just that: http://www.ibm.com/developerworks/mobile/worklight/getting-started.html#cordova

Related

SAPUI5 using cordova file to create config file

I'm try to create a config file to keep some configurations of my app. I'm using SAPUI5 and cordova file.
The intention is create a conf.txt to keep the URL, PORT and LDAP data to access my system. However, these information can change, so I need to update the file.
In my app, I've made the function deviceready when the application starts, and created the conf.txt:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
/*jQuery.sap.require("model.Config");
var conf = new Configuration();
conf.init();*/
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("conf.txt", {create : true,exclusive : false},gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
//alert(fileEntry.fullPath);
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
alert("OK");
};
var conf = "URL=\r\nPORT=80\r\nLDAP=false";
writer.seek(writer.length);
writer.write(conf);
}
function fail(error) {
alert(error.code);
}
I didn't do nothing different of other examples. But, as I've commented in onDeviceReady function, I tried to create a class to use to create the file, read and update it.
All examples that I found reference the deviceready event. Can I just use the methods of FileWriter and FileReader on this event?
It's my Configuration Class:
function Configuration() {
this.fileName = "conf.txt";
this.init = function() {**How to use the cordova API here**};
this.read = function(){**How to use the cordova API here**};
this.update= function(){**How to use the cordova API here**};
}
Thanks for help!
As suggested by Njtman, I got to save the informations in file without cordova file plugin just using localstorage.
I'd like to share the solution found.
index.html on deviceready event:
jQuery.sap.require("model.Config");
var conf = new Configuration();
sap.ui.getCore().setModel(conf, "Config");
conf.init();
Configuration class:
sap.ui.model.json.JSONModel.extend("Configuration", {
url: "",
port: "80",
defaultport: true,
ldap: false,
init : function() {
var deferred = $.Deferred();
console.log("INITIALIZING...");
var config = JSON.parse(window.localStorage.getItem("config"));
if(config == null){
console.log("CONFIG IS NULL");
window.localStorage.setItem("config", JSON.stringify(
{"URL": this.url, "PORT": this.port, "DEFAULTPORT": this.defaultport, "LDAP": this.ldap}
));
}
deferred.resolve();
this.setData(JSON.parse(window.localStorage.getItem("config")));
this.setVars();
console.log(this.getJSON());
return deferred.promise();
},
save: function(url, port, defaultport, ldap){
var deferred = $.Deferred();
console.log("SAVING...");
window.localStorage.setItem("config", JSON.stringify(
{"URL": url, "PORT": port, "DEFAULTPORT": defaultport, "LDAP": ldap}
));
deferred.resolve();
this.setData(JSON.parse(window.localStorage.getItem("config")));
this.setVars();
return deferred.promise();
},
setVars: function(){
this.url = this.getProperty("/URL");
this.port = this.getProperty("/PORT");
this.defaultport = this.getProperty("/DEFAULTPORT");
this.ldap = this.getProperty("/LDAP");
}
});
Now I can read and update my json file.

Cordova Phonegap File plugin FileWriter cordova.file

Why this works :
myFile1 = "myReadme.txt";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile(myFile1, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
alert("good");
}
function fail(error) {
alert("Error");
}
and that doesn't work ?
myFile2 = cordova.file.externalDataDirectory + "myReadme.txt";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getFile(myFile2, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
alert("good");
}
function fail(error) {
alert("Error");
}
Can we not use cordova.file.dataDirectory or cordova.file.externalRootDirectory or externalDataDirectory for Android ?
Thank you
I'm gonna try to answer with this issue (but I'm sure we can to do better ? )
First, when I plug my device to my computer the tree path is about like that :
MyFile1.txt
MyApplication
MyFiles
MyCache
Application
DCIM
media
Movies
Musics
Android
data
data (I think is not accessible when your are not rooted ???)
com.MyDomainName.MyAppName
cache
files
Then,
Following this official Cordova document : http://plugins.cordova.io/#/package/org.apache.cordova.file
, My first wish is to store my files and datas with "cordova.file.dataDirectory" or "cordova.file.externalDataDirectory" or another else ... ?
when you're doing console.log(cordova.file.dataDirectory) you obtain file:///data/data/com.MyDomainName.MyAppName/files/ => This, you cannot access when you are no rooted
and when you're doing console.log(cordova.file.externalDataDirectory) you obtain
file:///storage/emulated/0/
and when you're doing that
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) { console.log(fileSystem.root) ...
you can see in this object : nativeURL: "file:///storage/emulated/0/" ... so, it's the same like "externalDataDirectory" and I suppose we cannot use "dataDirectory" ...
Anyway, I don't know whether it's the best practice but here you are my solution :
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin, getDirectoryFail);
function onFSWin(fileSystem) {
fileSystem.root.getDirectory("myFolder", {create: true, exclusive: false}, getDirectorySuccess, getDirectoryFail);
}
function getDirectorySuccess(parent) {
console.log("New Folder or Folder already exists: " + parent.fullPath);
}
function getDirectoryFail(error) {
console.log("Unable to create new directory: " + error.code);
}
// Second, we gonna check or create a new file in a specific folder
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin2, onFSFail2);
function onFSWin2(fileSystem) {
fileSystem.root.getFile("myFolder/myFile1.txt", {create: true, exclusive: false}, gotFileEntry, onFSFail2);
}
function gotFileEntry(fileEntry) {
console.log("New file: " + fileEntry.fullPath);
fileEntry.createWriter(gotFileWriter, onFSFail2);
}
function gotFileWriter(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");
}
function onFSFail2(error) {
console.log(error.code);
}
You can use resolveLocalFileSystemURL to use the cordova.file.* properties:
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function (dirEntry) {
dirEntry.getFile("myFile1.txt", {
create: true,
exclusive: false
}, function (fileEntry) {
// fileEntry.createWriter
}, onError);
});

How to console.log() html with Phonegap

How do I write html to a text file using Phonegap? I'm trying to follow the example in the API documentation. The file creating works but I can't get console.log to work.
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log($("h1"));
};
}
function fail(error) {
console.log(error.code);
}
<body>
<h1>Example</h1>
<p>Write File</p>
</body>
Use "document.write" instead. It worked for me.
try to use
Log.d("info", "YOUR_TEXT");

read a text file from sdcard and display using phone gap

I have example.txt file sdcard and I want to display it using phone gap.I am very new to android and phone gap please help.
Here is my example.txt file:
<h2>This file is in sdcard</h2>
Here is my phonegap.java
package com.example.phonegap;
import org.apache.cordova.DroidGap;
public class Phonegap extends DroidGap{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/myfile.html");
}
}
and here is the myfile.html in www:
<!DOCTYPE html>
<html>
<head>
<title>FileReader Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Read File</p>
</body>
</html>
Change this line:
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
to be this:
fileSystem.root.getFile("example.txt", {create: false}, gotFileEntry, fail);
assuming that the file you want to read is "example.txt" and is located in the /sdcard folder.
I also encountered the same problem. I don't think the API document in Phonegap is right, so i referred JavaScript:the definitive guide, I found two key points:
the location of the file I am ready to read.
--> I found the default parent path is : /mnt/sdcard. So "/mnt/sdcard/temp/test.txt" file was written as fileSystem.root.getFile("temp/test.txt", null, gotFileEntry, fail)
after reader.readAsText(file), just using element.innerHTML = reader.result can't display the result in HTML file.
so I add a callback:
reader.onload = function(){
element.innerHTML = reader.result
}
After adjusting the two parts, my code works!
StackOverflow has very strict upload format policy, so I can't upload the exact code. But you can contact me to ask for the code.
I assume that the example.txt is at the root of SD card(Not resides in a folder). Then change following of your code,
function gotFS(fileSystem) {
fileSystem.root.getFile("file:///sdcard/example.txt", {create: true}, gotFileEntry, fail);
}
to
function gotFS(fileSystem) {
fileSystem.root.getFile("example.txt", {create: true}, gotFileEntry, fail);
}
And try by using alert in the below function,
function readAsText(file) {
alert("readAstext");
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
alert("content : "+evt.target.result);
};
reader.readAsText(file);
}
If that is not work, please add below code to your body tag in HTML
<body onload='onLoad();'>
Let me know issues you may faced.
Thanks,,

Writing and reading file in phonegap

I tried writing/reading a file in phonegap+android, here is the set up:
$(document).ready(function() {
document.addEventListener("deviceready", deviceready, true);
$(document).bind("deviceready", function(){
//writeFile();
//readFile();
});
});
function deviceready() {
writeFile();
readFile();
}
// This is just to do this.
function readFile() {
var d = navigator.file.read('/sdcard/foo.xml', success(), fail());
console.warn(d);
}
function writeFile() {
navigator.file.write('/sdcard/foo.xml', "This is a test of writing to a file",
success(), fail());
}
But on the emulator for Android 2.2, I got the following error message:
08-06 14:21:29.428: INFO/Web Console(936): Error in success callback: Network Status1 = TypeError: Result of expression 'navigator.file' [undefined] is not an object. at file:///android_asset/www/phonegap.0.9.6.js:649
What could be missing and what could be tried?
This also works in Android 2.2. You call the load(); function from body's onLoad, and writeFileFromSDCard(string) from some button's onClick, passing as parameter the string you want to write in the file.
<script type="text/javascript" charset="utf-8">
// Event listener
function load() {
document.addEventListener('deviceready', init, false);
}
// Called when device is ready - Do nothing
function init() {
}
// Called to write file to card
function writeFileFromSDCard(param) {
var writer = new FileWriter("/sdcard/write.txt");
writer.write(param + "\n", false);
alert("file Written to SD Card");
}
</script>
I would try using the FileReady and FileWriter APIs.
http://docs.phonegap.com/phonegap_file_file.md.html#FileReader
Here is what I came up with based on several links. I had been searching to do this as well. I used this site as a reference http://www.digitalnoiz.com/mobile-development/mobile-file-explorer-with-phonegapcordova-and-jquery-mobile-part-1/ as well as the Phonegap document api references
function displayMessage(msg)
{
navigator.notification.alert(msg);
}
function loadDirectories(fileSystem)
{
directoryEntry = fileSystem.root;
var directoryReader = directoryEntry.createReader();
directoryReader.readEntries(function(entries){
var sOutput = "";
for(var i=0; i < entries.length; i++)
{
if(!entries[i].isDirectory)
{
fileSystem.root.getFile(entries[i].name,null,gotFileEntry,fail);
}
}
//displayMessage(sOutput);
},fail);
}
function gotFileEntry(fileEntry)
{
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(evt){
displayMessage(evt.target.result);
};
reader.readAsText(file);
},fail);
}
function failFile(evt)
{
displayMessage(evt.target.error.code);
}
function fail(error)
{
displayMessage("Failed to list directory contents: " + error.code);
}
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady()
{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, loadDirectories, fail);
}
The following works for me on Android with phonegap-1.0.0:
<script type="text/javascript" charset="utf-8" src="css-js/phonegap-1.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
var path = "readme.txt";
fileSystem.root.getFile(path, {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write("some sample text");
</script>

Categories

Resources