Read local file in Phonegap

shadow_of__soul picture shadow_of__soul · Feb 11, 2013 · Viewed 10.8k times · Source

I'm trying to read a local file in Phonegap to load the language strings for the application and I can't make it work :(

The code is pretty straightforward:

var pathToLocalFile = "/home/user/android/assets/www/js/";
var langCache = new FileReader();
langCache.onload = function(data){
  col = JSON.parse(data);
  refreshAllStrings();
};
langCache.onerror = function(err){
  debug.error(err);
};
langCache.readAsText(pathToLocalFile+currentLang+'.json');

This code doesn't work on the Ripple emulator and I replaced it with

var pathToLocalFile = "file:///android_asset/www/js/";

in case of android, with the same result:

Uncaught TypeError: Object #<Console> has no method 'warning' cordova-2.4.0.js:2616
initRead cordova-2.4.0.js:2616
FileReader.readAsText cordova-2.4.0.js:2660    
loadLanguage

In the Ripple emulator, I started Chrome with google-chrome -–allow-file-access-from-files and the Android config and manifest has all the permissions for and the plugins set.

Of course I'm missing something, but any idea what this could be?

Regards.

Answer

codemonkey picture codemonkey · Feb 11, 2013

If the file is under the www folder of your app you don't need to add '/home/..' or 'file:///'. You should just be able to load the contents using an "AJAX" fetch even though it is bundled in the app.

$.get('js/filename.ext');