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>
Related
I'm trying to get external storage path in Phonegap. I'm using this code but it never handles the correct SDCard path.
(function(){
window.appRootDirName = ".myapp";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert(cordova.file.externalRootDirectory);
console.log("device is ready");
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
console.log("filesystem got");
fileSystem.root.getDirectory(window.appRootDirName, {
create : true,
exclusive : false
}, dirReady, fail);
}
function dirReady(entry) {
window.appRootDir = entry;
alert(JSON.stringify(window.appRootDir));
}
})();
also
<preference name="AndroidPersistentFileLocation" value="Internal" />
and
<preference name="AndroidPersistentFileLocation" value="Emulated" />
doesn't help.
Are there a way to get the correct SDCard path on Android 6 with phonegap?
This is how i made it work in android as well as in iOS,
function writeFile() {
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
}
function onError(e) {
alert("onError");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("Folder_Name", {
create: true,
exclusive: false
}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
// logic to write file in respective directory
};
function errorHandler(e) {
// handle error
}
Try out this one.
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("App_files", {create: false, exclusive: false}, onGetDirectoryWin, onGetDirectoryFail);
}
function fail(evt) {
console.log(evt.target.error.code);
}
var onGetDirectoryWin = function(parent) {
}
var onGetDirectoryFail = function() {
console.log("error getting dir")
}
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");
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
I am a phonegap newbie. I am trying to read and image file from sdcard in android using
phonegap official tutorial. The problem is that the image is not being displayed instead a question mark appears in its place.
My Code:
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
document.getElementById("test").innerHTML="onready about to request";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
edit:
Using API 16 and min-sdk8
"smallImage" is a tag it's working fine with onphotodatasuccess. So, camera is not a problem here. Everything related to camera functions is ok. Reading from sdcard is posing a problem at the assignment statement.
document.getElementById("smallImage").src = reader.readAsDataURL(file); if I add this i get the string and unknown chromium error -6, else i see the usual image converted string.
Thanks
Here is a working example :
EDITED:
<!DOCTYPE html>
<html>
<head>
<title>Pick Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);
}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
</head>
<body>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
This will allow you to pick any specified image from sdcard.
Hope this helps you.
Thanks.
try this:
<script>
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
//This file have to exist
var location= "file:///storage/emulated/0/DCIM/Camera/20141105_124208.jpg";
window.resolveLocalFileSystemURL(location, function(oFile) {
oFile.file(function(readyFile) {
var reader= new FileReader();
reader.onloadend= function(evt) {
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(readyFile);
});
}, function(err){
console.log('### ERR: filesystem.directoryUp() - ' + (JSON.stringify(err)));
});
</script>
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,,