Apache cordova - unable to write to file in android - javascript

I am trying to create a file in the PERSISTENT (sd card) storage using cordova's api in javascript. I am able to create the file, but unable to write data to it (data is empty on read). Below is my JS code:
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
writeTestList();
}
function writeTestList() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystemForWrite, function() { showMsg('Unable to access file system for write'); });
}
function gotFileSystemForWrite(fileSystem) {
fileSystem.root.getFile('testList.txt', {create: true, exclusive: false}, gotFileEntryForWrite, function() { showMsg('Unable to access file for write'); });
}
function gotFileEntryForWrite(fileEntry) {
fileEntry.createWriter(gotFileWriter, function() { showMsg('Unable to create test list'); });
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
// show a message
alert('created the test lists');
readSavedContent();
};
writer.onerror = function(evt) {
alert(JSON.stringify(evt));
};
writer.write("raj");
alert(writer.length);
}
The control always goes inside onerror of writer and on alerting the event obj, i see a type: "error", error: "JSON error". I completely don't get this. I am writing to a txt file, but getting json error. I have put write permissions in android manifest. Also, I have storage plugin for cordova enabled in config.xml preferences. People, pls help me out with this..!!

Unable to fix this issue in cordova 3.0. Moved to cordova 2.9 and everything works perfectly.

Related

Admob plugin dosen't work with Phonegap app

I hope you can help me with this problem. I have tried EVERYTHING the last 5 days, but I fail every time.
I have buildt a simple app using HTML5, CSS and little bit of Javascript.The app works fine.Than I want a simple banner ad that shows at the bottom of the app.I just can't get it to work. Sometimes a black box shows up at the bottom, that's all, but not ad. I'm not very good with Javascript so the problem is maby with the code, but I've copied most of it from plugin exemple.
Source: https://www.npmjs.com/package/phonegap-admob
I'm using:
- Phonegap 6.1.2 (Build Service)
- admob-phonegap plugin(<plugin name="phonegap-admob" spec="4.2.1" />)
- Other plugins that work fine.
What I need:
- Only a small banner ad at the bottom of the page.
Platform:
- Only Andriod
In my config.xml I have this line:
<plugin name="phonegap-admob" spec="4.2.1" />
In my index.html inside the <script></script> tags, I have this code:
<script>
var isAppForeground = true;
function initAds() {
if (admob) {
var adPublisherIds = {
android : {
banner : "ca-app-pub-1467389904102750/404191XXXX",
}
};
var admobid = (/(android)/i.test(navigator.userAgent)) ? adPublisherIds.android : adPublisherIds.ios;
admob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
});
registerAdEvents();
} else {
alert('AdMobAds plugin not ready');
}
}
function onAdLoaded(e) {
if (isAppForeground) {
if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
console.log("An interstitial has been loaded and autoshown. If you want to load the interstitial first and show it later, set 'autoShowInterstitial: false' in admob.setOptions() and call 'admob.showInterstitialAd();' here");
} else if (e.adType === admob.AD_TYPE_BANNER) {
console.log("New banner received");
}
}
}
function onPause() {
if (isAppForeground) {
admob.destroyBannerView();
isAppForeground = false;
}
}
function onResume() {
if (!isAppForeground) {
setTimeout(admob.createBannerView, 1);
setTimeout(admob.requestInterstitialAd, 1);
isAppForeground = true;
}
}
// optional, in case respond to events
function registerAdEvents() {
document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
document.addEventListener(admob.events.onAdFailedToLoad, function (e) {});
document.addEventListener(admob.events.onAdOpened, function (e) {});
document.addEventListener(admob.events.onAdClosed, function (e) {});
document.addEventListener(admob.events.onAdLeftApplication, function (e) {});
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);
}
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
initAds();
// display a banner at startup
admob.createBannerView();
}
document.addEventListener("deviceready", onDeviceReady, false);
</script>
I hope someone can help me. Thank you so much
Allright, the whole code was correct. The problem was just that I didn't link to Cordova in the Script tag. I read it somewhere that you didn't need it and Phonegap / Cordova would include it automatically. It was all that was needed. Do you want Admob to be displayed (and probably many other plugins), please include
<script type = "text / javascript" src = "cordova.js"> </script>.

Not able to get error in pubnub javascript callback

I am following the howto in this blog post: http://www.pubnub.com/blog/sending-android-push-notifications-via-gcm-javascript-using-phonegap/
Up til now I have done the following:
Created a new project in Google Dev Console
Turned on Google Cloud Messaging for Android
Got the sender ID (project number) and a server
key
Then added push plugin to existing project:
$ cordova plugin add https://github.com/phonegap-build/PushPlugin.git
Then copied PushNotification.js from the plugin to my js lib folder.
I am loading both this js file and the pubnub cdn with requirejs, which seems to work fine.
I created a module with the scripts from 2.2 in the howto.
define(['env-config','datastore/localstore','jquery','push','pubnub'],function (EnvConfig,Store) {
var pushNotification = window.plugins.pushNotification;
function register() {
pushNotification.register(
successHandler,
errorHandler,
{ 'senderID':EnvConfig.push.senderid, 'ecb':'onNotificationGCM'}
);
}
function successHandler(result) {
console.log('Success: '+ result);
}
function errorHandler(error) {
//** The following line throws:
//** java.lang.Long cannot be cast to java.lang.String
console.log('Error:' + error);
}
function onNotificationGCM(e) {
switch(e.event){
case 'registered':
console.log("Device registered with id "+e.regid);
Store.set("pushid"+e.regid);
/*if (e.regid.length > 0) {
deviceRegistered(e.regid);
} */
break;
case 'message':
if (e.foreground){
//What needs to be done when app is in the foreground
//while receiving a notification
console.log('A notification has been received');
}
break;
case 'error':
console.log('Error: ' + e.msg);
break;
default: console.log('An unknown event was received');
break;
}
}
var module = {
init: function() {
register();
}
};
return module;
});
When device is ready, I call the init function of this module.
At the moment register() fails and executes the errorHandler callback. But console.log fails with: java.lang.Long cannot be cast to java.lang.String. Therefore I have no idea what to do next...
Any pointers is much appreciated.
Samsung Galaxy S5
Android 4.4.2
Chrome 30.0 (in webview)
Cordova 3.6.3-0.2.13
Ah, I think I know what's going on-
Your sender ID has to be in string! You are probably using it as a number.
BTW, thanks for trying out the tutorial I wrote :-)

HTML5 WebWorker and Rails 3 Error

I am trying to implement an HTML5 WebWorker and I am using rails 3. I have this in my js code:
//When body(DOM) is ready
$(function() {
....
..
//test html5 webworkers
$('#test_html5_workers').click(function() {
var worker=new Worker('play.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
});
..
....
)};
and in another file I have this (in play.js)
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
I am currently getting this error:
Script file not found: play.js
I have tried other file path names with no luck.
Any ideas why I am getting this since both files are in the same directory, assets/javascripts?
I am using Firefox 17.0.1
The javascript file (play.js) should go in the public folder, or at least that's what I did to get it working.
This works on mine.
(function() {
//test html5 webworkers
$('#test').on('click', function(){
if(window.Worker){
var worker = new Worker('test.js');
worker.onmessage = function(e){
alert('worker said: ' + e.data);
}
worker.postMessage('start');
}
});
})();
//test.js
self.onmessage = function(e){
if(e.data === 'start'){
self.postMessage('booyeah');
}
}

Get all filenames using Phonegap file API

I am using Phonegap file upload to upload SVG files to my server. It's working fine. But I need to take all SVG files from the iPad's absolute path and send them to my server. I don't know how to get all .svg files using Phonegap's file API, so that I can send to the server looping through file names. Please tell me how to do this.
My code for file upload is:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("image5_2.jpg.svg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
var localpath=fileEntry.fullPath;
uploadPhoto(localpath);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
var ft = new FileTransfer();
ft.upload(imageURI, "http://192.168.1.54:8080/POC/fileUploader", win, fail, options);
}
You need to create a DirectoryReader from the root FileSystem and loop through all the entries looking for .svg files.
function gotFS(fileSystem) {
var reader = fileSystem.root.createReader();
reader.readEntries(gotList, fail);
}
function gotList(entries) {
var i;
for (i=0; i<entries.length; i++) {
if (entries[i].name.indexOf(".svg") != -1) {
uploadPhoto(entries[i].fullPath);
}
}
}
You may have to make some minor edits to this code but it should get you started.

How to read a file from an SD card in PhoneGap?

I am trying to follow the example that is provided on PhoneGap's documentation, except instead of calling the window.requestFileSystem... inside the onDeviceReady, I am calling that whenever I actually need to access a certain file. For some reason, my code does not seem to go past that line.
function pullSelectRecord(link)
{
selectedFile = link;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
alert("this is" + selectedFile);
fileSystem.root.getFile(link, null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert(evt.target.result);
};
reader.readAsText(file);
}
You can call requestFileSystem from anywhere. If you are not getting past that line you'll need to look in "adb logcat" to see what the error could be. Also, make sure your Manifest.xml has the write external storage permission.

Categories

Resources