working example of phonegap android integration with third party api - android

i'm new at phonegap. any guide or example of the process of linking an api such as http://openweathermap.org/. want to get data from this api on android app

Use jQuery mobile to parse data from any API.
Follow the code and example JSON given below.
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example, of course, relies on the structure of the JSON file:
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}

Related

How to set computer fallback url in firebase dynamic link in react native?

I am using firebase dynamic link in my react native mobile application, everything is working well as I want.
One thing I am not able to implement that is, I have created one HTML preview page to show preview on other social media. I have set fallback url for iOS, android. when I share that link it works well in android and iOS , when user not installed app then it redirect to my website page. But in computer when I hit that it not redirect me to my website page it open only preview page which I am passing in link parameter.
If I am use
otherPlatform:{
fallbackUrl:DEEPLINK_FALLBACK
}
Then it works but the preview not show the by default preview is showing of fallbackUrl url of OtherPlatform.
This is the complete code I am using to generate dynamic link in my react native app.
const buildVideoLink = async () => {
try {
const activityId = selectedPozzle?.activityId ? selectedPozzle?.activityId : ""
const pozzleId = selectedPozzle?.pozzleId ? selectedPozzle?.pozzleId : ""
const conentLink = FEED_PREVIEW_URL + pozzleId + "/preview/"
const link = await dynamicLinks().buildShortLink({
link: conentLink + "?activityId="+activityId+"&pozzleId=" + pozzleId,
domainUriPrefix: DEEPLINK_DOMAIN,
otherPlatform:{
fallbackUrl:DEEPLINK_FALLBACK
},
android: {
packageName: ANDROID_PACKAGE,
fallbackUrl:DEEPLINK_FALLBACK,
},
ios: {
appStoreId: '12345678',
bundleId: IOS_BUNDLE,
fallbackUrl:DEEPLINK_FALLBACK,
}
}
);
console.log("Pozzle_share_link........", link)
return link;
}
catch (error) {
}
}

how to protect my app from share to another?

I am a cordova/phonegap android developer, currently I have some free app and now I have plan to publish the paid app in playstore. But only one can purchase and share it to his/her friends, so they can use without pay. How can I protect it? I refer many things in internet but I am not got any solution.
I found the following cordova plugin
https://github.com/mobilino/Phonegap-android-license-plugin . But I am getting signature random values, no one match with LICENSING & IN-APP BILLING key. Or how can I use this plugin.
AndroidLicensePlugin.check(
function(data) { alert( JSON.stringify(data));},
function(errorString) { alert("error: " + errorString);}
);
Merbin, Not sure if you found your answer but here is what I have done.
When I want to share an Android App that I am selling I go to Google Play Dev and create a promotional code list and provide one of those promo code to friends.
Here is the code I have used with that same plugin.
//---------------------------
//---------------------------
function LicCheck() {
//Running HTTP vs. Native
try {
//Default none or error
setLicKeyValue(Number(99));
AndroidLicensePlugin.check(
function (data) {
licProcessJSON(data);
},
function (errorString) {
console.log('LicCheck() ERROR ' + errorString);
setLicKeyValue(99);
}
);
}
catch (err) {
setLicKeyValue(99);
console.log('LicCheck() - Error - default set to 99 (try later) ' + err)
}
}
//---------------------------
//---------------------------
function licProcessJSON(data) {
var appLicResponseCode = Number(1); //0:owns, 1:do not own
//data = {
// responseCode: 0,
// signedData: "0|-123456798|de.mobilino....", // 6 fields of | delimitered data
// signature: "" // the BASE64 encoded signature from Google
//};
console.log('data.responseCode ' + data.responseCode);
//They own the app
if (data.responseCode === 0) {
console.log('licProcessJSON() - Onwer True');
setLicKeyValue(0);
return;
}
//They do not own the app
if (data.responseCode === 1) {
console.log('licProcessJSON() - Onwer False');
setLicKeyValue(1);
return;
}
console.log('licProcessJSON() - No Data?');
setLicKeyValue(99);
}
//---------------------------------
//---------------------------------
function setLicKeyValue(value) {
localStorage.setItem(_licIndicator, Number(value));
}

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.

wikitude 3.01: adding some features between examples did not work properly

i downloaded the SDK of Wikitude 3.1, installed the samples into my Eclipse workspace and on my Gnexus everything works. I divide the questions in points so could be easier to answer:
I added the "onMarkerSelectedFn" method into the "limitingVisiblePois.js" file because i wanted to have my POIs clickable and when clicked, appear the information page like the 5.1 example. I added the method but it doesn't work and i haven't understand where i'm making mistakes. Each other file is the same for the 5.x samples.
Code of "limitingVisiblePois.js" edited by me
var World = {
markerDrawable_idle: new AR.ImageResource("assets/marker_idle.png"),
markerDrawable_selected: new AR.ImageResource("assets/marker_selected.png"),
markerDrawable_directionIndicator: new AR.ImageResource("assets/indi.png"),
markerList: [],
// called to inject new POI data
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData) {
PoiRadar.show();
document.getElementById("statusElement").innerHTML = 'Loading JSON objects';
var poiImage = new AR.ImageResource("img/marker.png", {
onError: World.errorLoadingImage
});
// TODO: call single POI-creation statement instead
for (var i = 0; i < poiData.length; i++) {
var singlePoi = {
//EDIT BRUS: adding the ID of each POIs
"id": poiData[i].id,
"latitude": parseFloat(poiData[i].latitude),
"longitude": parseFloat(poiData[i].longitude),
"altitude": parseFloat(poiData[i].altitude),
"title": poiData[i].name,
"description": poiData[i].description
};
World.markerList.push(new Marker(singlePoi));
}
document.getElementById("statusElement").innerHTML = 'JSON objects loaded properly';
},
// user's latest known location, accessible via userLocation.latitude, userLocation.longitude, userLocation.altitude
userLocation: null,
// location updates
locationChanged: function locationChangedFn(lat, lon, alt, acc) {
World.userLocation = {
'latitude': lat,
'longitude': lon,
'altitude': alt,
'accuracy': acc
};
},
//EDIT BRUS: Adding onMarkerSelected function
onMarkerSelected: function onMarkerSelectedFn(marker) {
// notify native environment
document.location = "architectsdk://markerselected?id=" + marker.poiData.id;
},
// called from slider.js every time the slider value changes
onSliderChanged: function onSliderChangedFn(value) {
if (value > 0) {
var valueMeters = value * 1000;
PoiRadar.setMaxDistance(valueMeters);
AR.context.scene.cullingDistance = valueMeters;
}
}
};
// forward locationChanges to custom function
AR.context.onLocationChanged = World.locationChanged;
2) I wasn't able to understand where the POIs latlong coordinates where declareated. In the same code posted ahead, there is the function
loadPoisFromJsonData: function loadPoisFromJsonDataFn(poiData)
but i don't understand how the poiData are taken.
I used the last 3.1 SDK in Android and phonegap.
thanks in advance,
Kind regards
Brus
PhoneGap Plugin samples are yet not in sync with those from the native SDK.
Whereat the current "HelloWorld" sample in PhoneGap Plugin requests POI-Data from a webservice the sample you pointed out is from the Android SDK and passes POI-data from native Android via "architectView.callJavaScript('loadPoisFromJsonData(...)')".
Both are making use of the same method to parse POI data, PhoneGap sample uses it e.g. that way
// request POI data
requestDataFromServer: function requestDataFromServerFn(lat, lon) {
var serverUrl = ServerInformation.POIDATA_SERVER + "?" + ServerInformation.POIDATA_SERVER_ARG_LAT + "=" + lat + "&" + ServerInformation.POIDATA_SERVER_ARG_LON + "=" + lon + "&" + ServerInformation.POIDATA_SERVER_ARG_NR_POIS + "=20";
var jqxhr = $.getJSON(serverUrl, function(data) {
World.loadPoisFromJsonData(data);
})
.error(function(err) {
alert("JSON error occured! " + err.message);
})
.complete(function() {});
}
You may just add these lines in your locationChanged implementation to use places from a dummy-webserver (don't forget to define 'alreadyRequestedData= false;' )
if (!World.alreadyRequestedData) {
World.requestDataFromServer(lat, lon);
World.alreadyRequestedData = true;
}
Kind regards,
Andreas

Connecting Android Application With CakePhp website

Is it possible to communicate an android Application with cakePhp website and share data? If it is possible, I want to create an application that can login into the website; my doubt is:
How to pass user name and password from our application to cakephp websites login page? Can anybody show me an example program?
How cakephp controller handle this request and respond to this request? Please show me an example program?
(I am a beginner in android and cakephp.)
Quick answer -- YES!
We just finished pushing an Android app to the market place that does this exact thing. Here's how we did it:
1) Download and learn to use Cordova PhoneGap (2.2.0 is the latest version) within Eclipse. This makes the whole thing so much easier with just some HTML and a lot of Javascript.
2) In your JS, create methods that push the login information using AJAX parameters. Example:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
$("#login").click(function() {
$email = $("#UserEmail").val();
$pass = $("#UserPassword").val();
$.ajax({
url : yourURL + 'api/users/login',
async : false,
data : {
'email' : $email,
'password' : $pass
},
dataType : 'json',
type : 'post',
success : function(result) {
/**
* do your login redirects or
* use localStorage to store your data
* on the phone. Keep in mind the limitations of
* per domain localStorage of 5MB
*/
// you are officially "logged in"
window.location.href = "yourUrl.html";
return;
},
error : function(xhr, status, err) {
// do your stuff when the login fails
}
});
}
}
3) In Cake / PHP, your Users controller here will take the username and password data in the AJAX call and use that for its authentication.
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('api_login');
}
public function api_login() {
$this->autoRender = false;
if ($this->request->data && isset($this->request->data['email']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'email'=> $this->request->data['email'],
'password' => $this->Auth->password($this->request->data['password']),
)
)
);
if (count($arrUser) > 0) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
// Do your login functions
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array( 'loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
}
?>
That's pretty much it. You are now authenticated to CakePHP.
You do not need to use "api_", you can use any function name you want, but this helped us keep a handle on what we allowed mobile users to do versus web users.
Now, these are just the building blocks. You basically have to create a whole version of your site on the phone using HTML and Javascript, so depending on your application it may be easier just to create a responsive design to your site and allow mobile browsing.
HTH!
Use Admad JWT Auth Plugin
If you use cakephp3 change your login function with this one :
public function token() {
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username (email) or password');
}
$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
You can read this tutorial about REST Api and JWT Auth Implementation
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
if rebuild most of the view pages in cakephp into ajax will seem defeat the purposes of using cakephp as it is.

Categories

Resources