Phonegap XMLHttpRequest upload progress - android

In my Phonegap 3.0.0 application I occasionally upload/download data.
As the upload migth sometimes reach up to couple of MB, I'd like to show to the user that progress is being made.
I wanted to accomplish this using xhr.upload "progress" event using code I found on the web
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log(percentComplete);
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something success-ish
}
});
No event on upload progress is however received when I test my app on Android 4.1.2 [S3 mini] and 2.3.4 [Xperia].
I should probably also mention that the upload is done cross-platform. and jQuery version is 2.0.3
Am I doing something wrong, or the built-in Android browser simply does not support this? Is there a way I could get this working?
Thanx for help

Related

How to redirect to app from WebBrowser in Expo

I am currently working on a project on Android using the Expo client for react native. I am trying to open a webpage using WebBrowser, passing my app development URI to the website. The website basically just redirects to the given URI after 5 seconds. However it never seems to open anything. I've used almost the exact same code as here: https://github.com/expo/examples/tree/master/with-webbrowser-redirect. When I load this project into expo and run, it redirects fine. However, when I copy the code for the website and app into my own project, website opens and displays, but redirect does nothing. It just stays there. Here is the code for opening the browser.
_openBrowserAsync = async () => {
try {
this._addLinkingListener();
let result = await WebBrowser.openBrowserAsync(
'https://wexley-auth.firebaseapp.com/?linkingUri=exp://192.168.1.2:19000'
);
this._removeLinkingListener();
this.setState({ result });
} catch (error) {
alert(error);
console.log(error);
}
};
The linking listener never fires the callback which should dismiss the browser. My app URI should be exp://192.168.1.2:19000 as expo developer tools shows me this when I connect over LAN. Ive also tried using Linking.makeUrl() instead of sending URI in string manually. Neither method works for me. Relevant website code:
document.addEventListener("DOMContentLoaded", function(event) {
var links = document.querySelectorAll('a');
var baseUri='';
// Take the uri from the params
var qs = decodeURIComponent(document.location.search);
if (qs) {
baseUri = qs.split('?linkingUri=')[1];
}
var redirectInterval = setInterval(function() {
var countdown = document.querySelector('.countdown');
var t = parseInt(countdown.innerText, 10);
t -= 1;
if (t === 0) {
clearInterval(redirectInterval);
window.location.href = baseUri;
}
}, 1000);
});
Am I missing a step? Do I need to setup a scheme for opening my app or should this work out of the box? Am I using the wrong URI? I noticed that in the example code, the app.json has the following fields that my app.json doesn't have:
"scheme": "expo.examples.with-webbrowser-redirect",
"platforms": [
"android",
"ios"
]

How to catch errors when downloading a file

Im using react-native-fs to download files from a server and to read the local system. Everything works great, however Im having an issue where I don't know how to catch the failure when downloading a file.
For example, if the user lost network, how can I catch that? What I want is to show an alert message to the user, hide the download percentage message that I'm showing and delete the uncomplete download.
I have the following code, but the catch never runs:
const result = FS.downloadFile({
fromUrl: url, // URL to download file from
toFile: `${CACHE_DIR}/${name}`, // Local filesystem path to save the file to
background: false,
progressDivider: steps,
begin: onBegin,
progress: onProgress,
readTimeout: 2 * MIN,
connectionTimeout: 30 * SEC,
});
return result.promise
.then(() => {
this.index[name] = {
name,
path: `${CACHE_DIR}/${name}`,
size: 0,
};
return this.index[name];
})
.catch((error) => {
console.log('error!', error); // <-- This code never runs :(
// Show and alert message to the user...
// Hide downloading message
// Delete incomplete download file
});
For now I'm only focusing on Android, but later on I will move on to iOS. I wonder if the same issue happens on iOS as well or if is only on Android.
Thank you so much for your help.
You can use the second callback of then
return result.promise
.then(() => {
this.index[name] = {
name,
path: `${CACHE_DIR}/${name}`,
size: 0,
};
return this.index[name];
}, (error) => {
console.log('error!', error); // <-- This code never runs :(
// Show and alert message to the user...
// Hide downloading message
// Delete incomplete download file
});

window.localStorage.setItem not working on mobile phone

I am working on HTML5 mobile app using jQuery mobile.
This is my code:
$(document).on("click","#send_mobile_number",function(){
var mobile = $('#mobile_number').val();
var user_id = sessionStorage.getItem("user_id");
$('.ui-loader').show();
$.ajax({
url: BASE_URL+'users/send_sms_code.php',
type: 'POST',
datatype: 'json',
data: "user_id="+user_id+"&mobile="+mobile+"&type=1",
async:false,
success: function (response) {
var data = jQuery.parseJSON(response);
$('.ui-loader').hide();
if(data.status == 'Fail') {
$('.very_mob_no_message').html('Sorry some error occurred,try again.');
}else{
$('#close_mob_popup').trigger('click');
setTimeout(function()
{
$('.click_mobile_verify').trigger('click');
}, 500);
$('#send_mobile_verify_span').hide();
$('#after_mobile_send_span').show();
$('#moble_number_div').hide();
$('#user_code_div').show();
$('#user_code').val(data.sms_code);
//alert(window.localStorage.getItem('mobile'));
//sessionStorage.setItem("mobile",mobile);
window.localStorage.setItem("mobile",mobile); // IT IS NOT WORKING
$('.very_mobile_message').html('Enter code which is <br/> sent to your mobile number.');
}
},
error: function (jqXHR, textStatus, errorThrown) {
//alert(jqXHR.status);
}
});
});
I want to store mobile number in session using window.localStorage.setItem("mobile",mobile);. It is working when I run on my browser but when I runt on mobile phone as APP it stop working. Why this happening. I am checking android phone.
Just use localStorage.mobile = "mobile". It's as simple as that. localStorage is a global object and can be accessed and manipulated as any other object. The only difference with regular objects is that it can store only strings.
You can then retrieve your value using alert( localStorage.mobile ); // will alert "mobile"
So finally found the solution, I need to set webSettings.setDomStorageEnabled(true); on android code and after this localstorage is working perfectlly.

How to login with Google OAuth2 using Angularjs inside Phonegap using ClientID and ClientSecret

I am trying to login from my Phonegap App using Angularjs (using the Ionic Framework) through Google OAuth2. Currently I am using the http://phonegap-tips.com/articles/google-api-oauth-with-phonegaps-inappbrowser.html for logging in. But it is creating really ugly looking code and quite a hard to understand code when I am using Angular-UI-Router for Ionic.
This issue seems to be spiralling around without any proper answers. I hope it should be solved now. The Google Angular Guys should help.
How to implement Google Auth in phonegap?
The closest topic is How to use Google Login API with Cordova/Phonegap, but this is not a solution for angularjs.
I had to transfer the javascript variable values using the following code:
var el = document.getElementById('test');
var scopeTest = angular.element(el).scope();
scopeTest.$apply(function(){
scopeTest.user = user;
scopeTest.logged_in = true;
scopeTest.name = user.name;
scopeTest.email = user.email;
});
I did the solution like this, where TestCtrl is the Controller where the Login Button resides. There is a mix of jquery based $.ajax calls, which I am going to change to the angualar way. The google_call function basically calls the google_api which is mentioned in the link mentioned above in phonegap-tips.
.controller('TestCtrl', function($scope,$ionicPopup) {
$scope.logged_in = false;
$scope.getMember = function(id) {
console.log(id);
};
$scope.test = function(){
$ionicPopup.alert({"title":"Clicked"});
}
$scope.call_google = function(){
googleapi.authorize({
client_id: 'CLIENT_ID',
client_secret: 'CLIENT_SECRET',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function(data) {
accessToken=data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
//$ionicPopup.alert({"title":JSON.stringify(data)});
$scope.getDataProfile();
});
};
$scope.getDataProfile = function(){
var term=null;
// alert("getting user data="+accessToken);
$.ajax({
url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken,
type:'GET',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
},
success:function(data)
{
var item;
console.log(JSON.stringify(data));
// Save the userprofile data in your localStorage.
window.localStorage.gmailLogin="true";
window.localStorage.gmailID=data.id;
window.localStorage.gmailEmail=data.email;
window.localStorage.gmailFirstName=data.given_name;
window.localStorage.gmailLastName=data.family_name;
window.localStorage.gmailProfilePicture=data.picture;
window.localStorage.gmailGender=data.gender;
window.localStorage.gmailName=data.name;
$scope.email = data.email;
$scope.name = data.name;
}
});
//$scope.disconnectUser(); //This call can be done later.
};
$scope.disconnectUser = function() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken=null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----"+accessToken);
},
error: function(e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
}
});
};
})
I am providing this answer for the newbies who faced similar problems like mine while trying to login using Google OAuth2. So asking for Upvotes shamelessly as I am new here too!

phonegap WFS proxy issue

I encountered a problem when I try to package my sencha-touch app using phonegap. Everything works fine except accessing WFS in phonegap. (And the app has no problem running in browser, WFS access is OK)
My phonegap version is 2.9; openlayer version is 2.13
Here I present my simple code. You can also check the example codes in the following site: http://openlayers.org/dev/examples/wfs-filter.html
var rootUrl = window.location.protocol + "//" + window.location.host + '/';
var map;
function init() {
map = new OpenLayers.Map({
div: "map",
layers: [
new OpenLayers.Layer.WMS(
"Natural Earth",
"http://demo.opengeo.org/geoserver/wms",
{ layers: "topp:naturalearth" }
),
new OpenLayers.Layer.Vector("WFS", {
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: new OpenLayers.Protocol.WFS({
url: rootUrl + 'proxy.py?url=http://demo.opengeo.org/geoserver/wfs',
featureType: "tasmania_roads",
featureNS: "http://www.openplans.org/topp"
}),
styleMap: new OpenLayers.StyleMap({
strokeWidth: 3,
strokeColor: "#333333"
}),
})
],
center: new OpenLayers.LonLat(146.7, -41.8),
zoom: 6
});
}
In phonegap there's no problem accessing WMS, but when I try WFS, it never work.
Comparing to the link I showed you before, there's a road displayed in the map, and it is obtained through WFS. In my phonegap app, the road will not be displayed.
I'm wondering whether it is a WFS issue, or phonegap issue. Something is blocking my access to WFS in my phonegap app.
Please give me some suggestions and hints, guys! I will really appreciate it.
function getLayerList() {
$.ajax({ url: rootUrl + 'proxy.py?url=http://192.168.0.23/LBEService/Service1.svc/GetEventList',
//async: false,
data: JSON.stringify({}),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
$("#demo").html(result[0].event_NAME);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}).done(function () {
});
}
Have you added the domain that is hosting the WFS to the white list?
http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
On android PhoneGap window.location.protocol is 'file:' and window.location.hostname is "", so your app will probably be looking for file://proxy.py? which doesn't exist on your device.
To solve this issue I test the protocol, and set up OpenLayers.Proxy accordingly, thus:
if( location.protocol == 'file:' ) {
OpenLayers.ProxyHost = "";
} else {
OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url=";
}
So in your case, if protocol is 'file:', I think you need to drop 'proxy.py?'
Tip: debug your android app using Chrome on your PC (chrome://inspect/#devices) and you'll see the request that android is making.

Categories

Resources