read a text file from sdcard and display using phone gap - android

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,,

Related

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");

Combining native app with worklight project

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

Unable to read image files from sdcard in phonegap: android

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>

Choose an image from camera or gallery using phonegap

<script type="text/javascript" charset="utf-8">
var pictureSource; // Picture source
var destinationType; // Sets the format of returned value
// Wait for PhoneGap to connect with the device
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready to be used!
function onDeviceReady()
{
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 25, destinationType:
Camera.DestinationType.FILE_URI });
}
function onPhotoURISuccess(imageURI) {
createFileEntry(imageURI);
}
function createFileEntry(imageURI) {
window.resolveLocalFileSystemURI(imageURI, copyPhoto, fail);
}
function copyPhoto(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory("photos", {create: true, exclusive: false},
function(dir) {
fileEntry.copyTo(dir, "file.jpg", onCopySuccess, fail);
}, fail);
}, fail);
}
function onCopySuccess(entry) {
console.log(entry.fullPath)
}
function fail(error) {
console.log(error.code);
}
</script>
You should use the PhoneGap 2.0.0 camera object. The documentation provides a full photo capturing example.
Furthermore the navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] ); takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file.
I hope this helps.

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