I'm working on mobile app through XDK intel, How can I read text file from outside the app?
I tried this code, but it's not working!
function readFile (filepath){
var txtFile = "C:\test.txt";
var file = new File(txtFile);
file.open("r"); // open file with read access
var str = "";
while (!file.eof) {
// read each line of text
str += file.readln() + "\n";
}
file.close();
alert(str);
}
You are building a Cordova app (aka PhoneGap app) when you are creating an app for the Intel XDK. So the rules (and solutions) that apply to Cordova also apply to Intel XDK apps. The XDK is simply providing a way to make it easier to apply and use the standard Cordova tools, it is not providing a different runtime environment (other than including the option to replace the Android webview with a Crosswalk webview).
This describes, at a very high level, what Cordova and Cordova plugins do on an Android device > http://developer.android.com/guide/webapps/webview.html. Similar approaches are taken on iOS and Windows and other platforms supported by Cordova.
As Nicolas stated in his answer, you should use the Cordova File Plugin. On the doc page for that plugin you'll find two references that are worth reading:
http://cordova.apache.org/docs/en/latest/cordova/storage/storage.html
http://www.html5rocks.com/en/tutorials/file/filesystem/
Also, these may be of value:
http://www.html5rocks.com/en/features/storage
http://developer.android.com/training/basics/data-storage/files.html
http://developer.android.com/guide/topics/data/data-storage.html
Related
I am working on a hybrid tizen app(web + native service) for Samsung Gear Fit2 Pro. I want to create/setup a config from web ui app and save it into data path of the app so that the native service can load the config and use it.
I am trying to create a config.txt file from tizen web app at /opt/usr/apps/pkg-id/data. I've tried using filesystem API of tizen with proper privileges but it always shows those API functions are undefined. However, if I use resolve then file creation works only for some directories like documents. But I want to create a file if not exists in my app's data folder i.e. /opt/usr/apps/pkg-id/data or modify it if already exists. Relevant portion of my code that tries to write to a file in data folder is shown below.
Is there any way to do that? Or am I doing something wrong while using the file-system api?
function app_get_datapath() {
return "/opt/usr/apps/"+tizen.application.getCurrentApplication().appInfo.packageId+"/data/";
}
var fileHandleWrite = tizen.filesystem.openFile(app_get_datapath()+'config.txt', 'w');
fileHandleWrite.writeString(tizen.systeminfo.getCapability('http://tizen.org/system/tizenid'));
fileHandleWrite.close();
Here are the list of privileges:
I've tried using filesystem API of tizen with proper privileges but it always shows those API functions are undefined.
Samsung Gear Fit2 Pro does not support all new APIs. Probably you should refer to Tizen 3.0 API, but the API you use in code snippet is supported since Tizen 5.0
My second comment is that you should not use paths built 'by hand' via string concatenation as you do in app_get_datapath(). It is highly non-portable solution, which can NOT work on some devices. Instead I would suggest using built-in virtual root for getting your application private storage - wgt-private, which will automatically return valid path on a device (no matter what the device is).
Example (using only 3.0 API, for 5.0 it would be much easier):
(function createConfig() {
function writeConfig(file) {
file.openStream('w', function (stream) {
stream.write(tizen.systeminfo.getCapability('http://tizen.org/system/tizenid'));
stream.close();
console.log('All done!!')
})
}
tizen.filesystem.resolve("wgt-private/config.txt", function (file) {
console.log('Config file exists - overwrite');
writeConfig(file);
}, function (e) {
console.log('Config file does not exist - create');
tizen.filesystem.resolve("wgt-private", function (dir) {
var file = dir.createFile("config.txt");
console.log("Created file")
writeConfig(file);
});
});
})()
I'm writing an app using Ionic 5, Angular and Cordova. I would like to get the "platform" variable used to build my application (i.e. the argument used in a command like "ionic cordova build android).
Unfortunately, all I found on the web was the Platform service (https://ionicframework.com/docs/angular/platform), useful but not quite what I needed (e.g. platform.is('android') can return true if the application runs on a web app on an android phone, on a browser on an android phone or if I click F12 on chrome...).
What I need is to find the platform the application was built for.
The best way I found to achieve the result, was to add "build:before" hook in my ionic.config.json file
"hooks": {
"build:before": "scripts/build-before.js",
"build:after": "scripts/build-after.js"
}
and change the constant in a service before building
#!/usr/bin/env node
var process = require('process');
var fs = require('fs');
let input=process.argv;
let android="android";
let browser="browser";
let ios="ios";
let platformFile="MYFILE"
module.exports = function() {
let nbArgs=input.length;
let platform;
for(let i=0;i<nbArgs;i++){
if(input[i]==android){
platform=android;
}
if(input[i]==browser){
platform=browser;
}
if(input[i]==ios){
platform=ios;
}
}
let file = fs.readFileSync(platformFile, 'utf8');
let replacement="MYSTART '"+platform+"';";
let result = file.replace(/MYREGEX/g, replacement);
fs.writeFileSync(platformFile, result);
console.log("Service updated with platform: "+platform);
}
Then in the build:after I restore the file as it was (to avoid to commit the file on GIT after each build...).
I added the code in case someone has the same issue and looks for a quick workaround.
My question is: does anyone know of an official/smarter way to achieve the result?
Thanks,
I'm not entirely sure of what your goal is, but detecting the platform where the app is running is way easier than that. For example, if you want to know if the app is being executed on an Android mobile device, you could use the following condition:
if(this.platform.is('mobile') && this.platform.is('android')) {
// ...
}
In a similar way, you can check if the device is a desktop, a pwa, ... or any other combination based on the following list:
https://ionicframework.com/docs/angular/platform#platforms
android: a device running Android
capacitor: a device running Capacitor
cordova: a device running Cordova
desktop: a desktop device
electron: a desktop device running Electron
hybrid: a device running Capacitor or Cordova
ios: a device running iOS
ipad: an iPad device
iphone: an iPhone device
mobile: a mobile device
mobileweb: a web browser running in a mobile device
phablet: a phablet device
pwa: a PWA app
tablet: a tablet device
here's my situation. I have a html +css + jquery well working project that I want to adapt in titanium. This project has geolocation + fb api call.
I want to adapt my project into a titanium html5 project. What I found is that I can call titanium api only through addEventListener and fireEvent functions (of course only if I use webviews).
it' my first titanium project I work with that needs geolocation and facebook api.
actually, I started to modify the previous project by adding addEventlistener into the app.js file and fireEvents into the javascript files of the previous project ( included in the first project in the html files) in the parts that need the titanium api calls (I can't call titanium api outside of app.js).
the problem is that I need some values (objects) to be returned back.
to better understand what I'm doing, here's the sequence of the events.
TITANIUM PROJECT
(app.js)
var win = Ti.UI.createWindow();
var webview = Ti.UI.createWebView({
url: 'index.html'
});
Ti.App.addEventListener('geolocation',function(){
//some titanium api call
lat = x;lon=y;
Ti.App.fireEvent('geolocation_back',{latitude:lat,longitude:lon});
});
win.add(webview);
win.open();
HTML + CSS + JS PROJECT
(imported file into index.html, not imported into app.js)
Ti.App.fireEvent('geolocation');
var my_lat ;
var my_lon ;
Ti.App.addEventListener('geolocation_back',function(d){
my_lat = d.latitude;
my_lon = d.longitude;
//do other stuff with my_lat and my_lon
});
I hope you understand what I'm doing.
my questions are:
1) is what I am doing the correct way to work with titanium and html code?
2) is there anyother way to call titanium api within html code and return variables/objects back?
EDIT
this code works only on iOS and android but not on web browser. it seems that the built in server (Titanium studio or Android web browser emulator) doesn't load the Ti.* or Titanium.* objects. is there anyway to make it works on web browser?
I see the web mobile compiler creates all the titanium API in subfolders
there is titanium.js and TI/* folder. can anyone explains me why the console says me Ti is not defined?
as I said here
I found a solution!
simply add to all of your html pages the simple script below
var Ti = window.parent.Ti
have fun!
I'm looking for a pdf viewer for Android using Phonegap 2.0. I tried the childbrowser plugin which worked on iOS but not on Android. I tried this http://www.giovesoft.com/2011/08/download-and-open-pdf-with-phonegap.html but that didn't work either, I get error messages like PhoneGap is not defined at file and cannot call method "showPdf" of undefined.
you can use pdf.js :
pdf.js is an HTML5 technology experiment that explores building a
faithful and efficient Portable Document Format (PDF) renderer without
native code assistance.
https://github.com/mozilla/pdf.js
I answered a similar question already (see Open PDF with PhoneGap in Android) but will do the same here. Use the ChildBrowser plugin as suggested in conjunction with Google Docs like so:
onclick='window.plugins.childBrowser.showWebPage(encodeURI("http://docs.google.com/viewer?url=' + pdfLink + '"));
This works fine for me and I have tested it in Android 2.1 up to 4.1.
The childbrowser plugin which I tried with does not open the pdf in android phonegap. However, it works for iOS. Another solution to your plugin query could be to use the Open With plugin. There is one disadvantage that this plugin does not open the pdf in the app itself. You can use the downloader plugin to download files and then try out the childbrowser plugin to access this pdf, which I think should be the solution
In Android, you can view the pdfs using Android Intents. This will show you all the pdf viewers available in your phone. You can select any and view the pdf
Eg :
private void showPdfAndroid(String url) throws IOException {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(url);
String extension = url.substring(url.lastIndexOf(".")+1);
String type = "";
if (extension.toLowerCase().equals("pdf")) {
type = "application/pdf";
Log.d("application/pdf", "application/pdf");
}
intent.setDataAndType(Uri.fromFile(file), type);
cordova.getActivity().startActivity(intent);
Log.d("FileViewerPlugin", "View complete in" + url);
}
Child browser don't support pdf viewing in android . better you use Google docs viewer for it in android . here in another stack overflow question you will get complete answer
What is the most efficient and reliable method to detect if an app is running in phonegap, or simply inside of a mobile/desktop browser with JavaScript? I am attempting to eliminate any of the issues that prevent me from testing/debugging my phonegap apps in any browser (desktop or mobile), and create a truly universal code base for my apps.
I intend on structuring my functions with phonegap specific calls like so:
if (phonegapisrunning) {
// phonegap specific javascript calls here
}
else {
// standard javascript calls here
}
While searching for a solution I came across this thread:
PhoneGap: Detect if running on desktop browser.
While this thread discusses this issue, I do not see a clear answer to which method is the most efficient/reliable. Should I bind to the onDeviceReady() event? Should I check window.device? Is there a more efficient or reliable way to check if an app is running in phonegap via JavsScript?
And this thread which mentions the Ripple Chrome Plugin:
Phonegap web app in regular desktop browsers
The Ripple tools looks like it could be a valuable tool for testing. But I am trying to make my phonegap apps run in a desktop browser without a plugin.
If it is determined that the app is not running in phonegap, I would then use useragent sniffing to determine if browser is desktop or mobile, and further separate any code if needed.
I've seen many answers about checking the user agent. Though those are useful for comparing which platform on which a page was loaded, they still do not differentiate whether running within a cordova app's browser or within a regular web browser. After a whole bunch of digging in the android cordova javascript file, I found that the following variable is set when running in a cordova app:
window._cordovaNative
Looking through the ios cordova javascript, I found:
window._nativeReady
Throw these alerts in your page before you ever load any cordova javascripts or check any user agents, etc. and compare results between loading from a web browser and loading from a cordova app that gets dynamic content:
alert("Android: " + window._cordovaNative);
alert("iOS: " + window._nativeReady);
I guess the other devices' phonegap files have different global variables, but for now, this is going to work great for me -- I hope it works well for you!
My suggestion is to create/call your javascript functions outside of the onDeviceReady Phonegap call.
Or maybe check what version of Cordova / Phonegap is running e.g.:
var string = device.cordova; // or device.phonegap
if (string == null) {
//do non phonegappy stuff here
} else {
//do phonegappy stuff
}
While it may not be the cleanest solution, a simple and reliable method is to create/set a global variable on deviceready:
var isCordovaReady = true;
Then:
if (isCordovaReady) {
// do cordova/phonegap stuff
}
else {
// do non cordova/phonegap stuff here
}
I posted the top answer for: PhoneGap: Detect if running on desktop browser
Although this isn't heavily documented and somewhat controversial I've been able to use this chunk of code for all my projects:
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
document.addEventListener("deviceready", onDeviceReady, false); //phone
} else {
onDeviceReady(); //this is the browser
}
You can modify it a bit to work for your projects like so:
var phonegapisrunning = false;
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
document.addEventListener("deviceready", onDeviceReady, false); //phone
//change to true
phonegapisrunning = true;
} else {
onDeviceReady(); //this is the browser
}
Hope this helps !