Android- Sharing local storage on multiple WebViews/Windows - android

I'm developping a mobile application, which should connect to a web server. The application is written with jQM and simply imported in an android web view. I tried to solve this problem using the jStorage plugin, but it seems that it's impossible to share the local storage between the different pages. So I tried to implement this, but it does not work and continues sending null.
Here are my code samples:
Javascript:
function getToken(authCode) {
var jsonUrl = mainUrl + "/auth/authorizeToken?grant_type=authorization_code&client_id=bc89fb879a64eb8e422b94d5c39&client_secret=b5c2974b78f7f3f7aee2bed182&redirect_uri=redirection&code="+authCode;
$.ajax({
url: jsonUrl,
type: "GET",
dataType: "jsonp",
success: function(data) {
localStorage.setItem( "access_token", data.access_token);
localStorage.setItem( "refresh_token", data.refresh_token);
localStorage.setItem( "logged", "true");
}
});
}
function valTokens() {
access_token = localStorage.getItem("access_token");
refresh_token = localStorage.getItem("refresh_token");
}
After that the values are set to null. The .java files are the same as in the sample from the link given.

Related

How to Download and view profile picture in ionic 3 with sharepoint?

Iam new in ionic with sharepoint
I have developed a Mobile app using ionic3 with sharepoint.
Now i have to get user profile picture in my app.
I have tried these are the way can't achieve here is my tried code.
First way tried like this
Passing Url:-
"https://abc.sharepoint.com/sites/QA/_layouts/15/userphoto.aspx?size=M&accountname=admin#abc.onmicrosoft.com"
Second way tried like this
Passing Url:-
These url iam geting using people picker result. PictureURL property
"https://abc.sharepoint.com/User Photos/Profile Pictures/admin_abc_onmicrosoft_com_MThumb.jpg"
These Second method always return
401 UNAUTHORIZED
Above url using to call this method.
public downloadFile(url: string, fileName: string) {
let options = this._apiHeaderForImageURL();
this._http.get(url, options)
.subscribe((data) => {
//here converting a blob to base 64 For internal view purpose in image src
var reader = new FileReader();
reader.readAsDataURL(data.blob());
reader.onloadend = function () {
console.log("Base64", reader.result);
}
//Here Writing a blob file to storage
this.file.writeFile(this.file.externalRootDirectory, fileName, data.blob(), { replace: true })
.then((success) => {
console.log("File Writed Successfully", success);
}).catch((err) => {
console.log("Error While Wrinting File", err);
});
});
}
public _apiHeaderForImageURL() {
let headers = new Headers({ 'Content-Type': 'image/jpeg' });
headers.append('Authorization', 'Bearer ' + localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers, responseType: 3 });
return options;
}
The first api call worked fine result also sucess but image not displayed properly. Thats the problem iam facing.
The result comes an default image like this only.
pls help me to achieve this. Any help warmly accepted.
Iam doning long time stuff to achieve this still i cant achieve pls give some idea.
Is any other way is available to get user picture in ionic 3 using sharepoint?

MVC 4 Web API 2 ajax call all parameters optional

I realy want your option.
We update a .net MVC 3 project to MVC 4 with web api 2, this a web service.
The ajax calls is from android machines with the Devextreme/Phonegap.
After the update the web service when i call login from android i get
"No HTTP resource was found that matches the request URI 'http://www.whatever.gr/MVCService/Actions/Login'"
I want to set the route so that all methods of the MVC service can have parameters optional.
I can't get this work..
We can't change the source on the android app,and ajax call is the code below
function doLogin(username, password, callback) {
loading(true);
var dataStr = "uid=" + uid + "&username=" + username + "&password=" + password;
var success = false;
var token = "";
$.ajax({
type: "POST",
url: registrationServiceUrl + 'Login',
data: dataStr,
beforeSend: function () {
//alert("registration no: " + registrationid);
},
success: function (retval) {
if (retval.indexOf('SUCCESS') == 0) {
success = true;
token = retval.substring(8);
//setTokenToSettings(token);
} else {
success = false;
};
callback(success, token);
loading(false);
},
error: function (retval) {
callback(success, token);
loading(false);
}
});
}
The route in MVC is
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
When i hit like below with parameters in a browser i have a response
'http://www.whatever.gr/MVCService/Actions/Login?param1=1&param=2&param3=3'.
I want to have the behavior, when to hit 'http://www.whatever.gr/MVCService/Actions/Login'
or
'http://www.whatever.gr/MVCService/Actions/Login?param1=1&param=2&param3=3&invalidParamName=x'.
And the web service method to be trigger with empty parameters values.
But without setting optional parameters in the method
public string Login(string pamar1 = "",string param2 = "", string param3 = "")
With MVC 3 this was working fine as I explained before.
Thanks in advance and for your time.
In Web API, it's very simple to remember how parameter binding is happening.
if you POST simple types, Web API tries to bind it from the URL
if you POST complex type, Web API tries to bind it from the body of
the request (this uses a media-type formatter).
This asp.net page explains it all.
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

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!

How do I enable Third-Party Cookies under Phonegap and Android 3.2?

I am using $getJSON to hit a node.js endpoint under Phonegap and Android. The code looks like this
$.getJSON(
serverURL + "/login?callback=?",
"playerId=" + playerId + "&pwd=" + pwd,
function(data){
theCallbackFunction.call(null, JSON.parse(data));
},
function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
);
In response to the login request, my server sends back a session cookie. This cookie is only accepted and returned in subsequent AJAX requests if 'Third-Party Cookies' are enabled in the browser. I have found that older Android devices (e.g. 2.2) allow this by default but new ones (3.2) do not.
Is it possible to force Phonegap to enable Third-Party Cookies for my Android application?
I had a similar problem when trying to authenticate with my server. I instead resorted to the use of localStorage. See the code below or here.
var store = window.localStorage,
request = {
url: {SERVER_URL},
headers : {
Cookie: store.getItem('session')
},
complete: function (jqXHR, status){
if (status != 'success') {
console.log('ajax status: failure');
} else if (store.getItem('session') != null) {
console.log('ajax status: session exists');
} else {
console.log('ajax status: saving cookie');
var header = jqXHR.getAllResponseHeaders();
var match = header.match(/(Set-Cookie|set-cookie): (.+?);/);
if (match) {
session = match[2];
store.setItem("session", session);
}
}
}
}
$.ajax(request);
In the above, I'm checking for the localStorage variable 'session' and if it exists, it will send the stored cookie. If it doesn't exist, it will take the 'set-cookie' paramater sent in the headers by the server, match the pertinent part and store it in the 'session' variable of localStorage.
Phonegap does not support cookie abstraction. Never really needed to as there are already apps/plug-ins that do. Plus it is intended to wrap up the functionality of the phone/device, not the browser. You CAN however do this with a jQuery plug-in.
https://github.com/carhartl/jquery-cookie

Categories

Resources