Recommended way to sync information between devices - android

I'm currently developing and I came up to the following question:
How can/should I store basic information, such as unlocked items and levels between devices.
Of course, I store them within preference files.
But what if the user buys a new phone and wants to continue playing on there?
(Shared-)Preferences won't be duplicated.
Thus, is there any (from google) recommended way (cloud?) to solve this issue?

I'm no expert, but the way I do this is with an online SQL database. Have the device connect to it, and save/load any data you need. I know this will not work with files, only text-based information. I also do this using Flash. If this is your route I can share some code.
Ok, so you need 3 things if you are doing this in flash: Flash (duh), PHP files, and a SQL server (I have a MYSQL server).
How it will work is flash will load php, php will do it's thing (like making changes to the database) and spit back it's results to flash.
Let's say we want to get all usernames from the database.
Database
The table name is called "Players" with a single column called "u_id"
Flash
var loader:URLLoader; //makes a loader that will "load" the php page
public function DoIt()
{
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, loaderComplete);
loader.load(new URLRequest("http://yourDomain.com/thePHPFile.php?arg=42"));
}
public function loaderComplete(e:Event):void
{
var returnXML:XML; //we are assuming the return values are in xml format, trust me, this might be easier
for each (var ListItem:XML in returnXML..Users) //you might need to change this "users" to be the root of the xml file
{
var userName:String = ListItem.u_id.toString();
//you can do what you want with the data here
}
}
PHP
Now it might not be required, but I try to make sure the PHP files and the DB is on the same host, so that I can do "localhost" as the host name
<?php
$argumentVar = $_GET["arg"]; //not using this, just showing it's possible
$connect = mysql_connect("localhost", "db_username", "db_password");
if(!$connect)
{
die("error connecting to DB" . mysql_error());
}
$db_selected = mysql_select_db("the_name_of_the_db", $connect);
if(!$db_selected)
{
die("error selecting db" . mysql_error());
}
$table_name = "Players" //this is the name of your database
$sql = "SELECT * FROM $table_name;"; //not sure if you need ending ';'
$dbresult = mysql_query($sql, $connect); //this is where all your data comes into
//and now to save all the information to a xml file
$doc = new DOMDocument('1.0');
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
while($row = mysql_fetch_assoc($dbresult))
{
$occ = $doc->createElement($table_name);
$occ = $root->appendChild($occ);
foreach ($row as $fieldname => $fieldvalue)
{
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}
}
$xml_string = $doc->saveXML();
echo $xml_string;
?>
Ok, go play with that, it should start you on the right path.

i think the best way would be to have an online database be maintained which is regularly updated with the latest information for every registered user. So instead of storing everything locally it can be stored on a remote server and sent to the user as and when required. so as long as the user owns the account created by himself for the application, no data will be lost.

Related

Android- Parse Database edit other users' information

I'm working on a school project that is a transportation application on android.
I'm trying to edit user information from another user as logged in. When I try to edit another user's saved variable, I get
java.lang.IllegalArgumentException: Cannot save a ParseUser that is
not authenticated.
On my search, I saw that some people recommend changing ACL to public write on the users to edit them, I tried that and unfortunately, It didn't change anything, I still have this error. Another advice was to use cloud code or master key but I couldn't find any documentation that shows how to implement them. I'd be glad if anyone helps me. Thank you very much.
you can use masterKey in cloud code like this:
otherUser.save(null,{useMasterKey:true});
Here is a complete example using cloud code and master key:
Parse.Cloud.define("saveOtherUser", async (request) => {
const otherUserID = request.params.otherUserID;//other user's ID;
const user = request.user; //This is you. We are NOT gonna update this.
//you can check your security with using this user. For example:
if(!user.get("admin")){
//we are checking if th requesting user has admin privaleges.
//Otherwise everyone who call this cloud code can change other users information.
throw "this operation requires admin privilages"
//and our cloud code terminates here. Below codes never run
//so other users information stays safe.
}
//We create other user
const otherUser = new Parse.User({id:otherUserID});
//Change variables
otherUser.set("variable","New Variable, New Value");
//Now we are going to save user
await otherUser.save(null,{useMasterKey:true});
//this is the response our android app will recieve
return true;
});
This is our Java code for android app:
HashMap<String, Object> params = new HashMap<>();
params.put("otherUserID", otherUser.getObjectId());
ParseCloud.callFunctionInBackground("saveOtherUser", params, new FunctionCallback<Boolean>() {
#Override
public void done(Boolean object, ParseException e) {
if(e==null&&object){
//save operation successful
}
else{
//save operation failed
}
}
});
Aklına takılan olursa sor :)

How to have all the data from my meteor+cordova app stored in a common database?

I've a meteorjs app which I'm making for android devices (mobile app) using cordova and it has a form for placing orders which, after submitting, the data should be shown in a common database where the moderators can check the data entries and edit/delete as required.I've been suggested to use mongohq/mongolab but I'm confused and wondering if those will be able to meet my requirements.
Here's my database code which inserts all the information of the form after submitting:
Template.shop.events({
'click #submit':function(evt,tmpl){
evt.preventDefault();
var name = tmpl.find('.name').value;
var email = tmpl.find('.email').value;
var phone = tmpl.find('.mobile').value;
var delivery=tmpl.find('.delivery').value;
var apple=tmpl.find('.apple').value;
var pear=tmpl.find('.pear').value;
var pineapple=tmpl.find('.pineapple').value;;
var address=tmpl.find('.address').value;;
var date=new Date();
Shop.insert({
name:name,
email:email,
phone:phone,
delivery:delivery,
apple:apple,
pear:pear,
pineapple:pineapple,
address:address,
time:date.toLocaleDateString()+' at '+date.toLocaleTimeString()
});
alert('Your form has been submitted!');
Session.set('adding_cart', false);
}
});
In short both your cordova version and your web version will use the same database.
Longer Answer
After checking the collection.allow on the client it will send a call to the server, which will check the collection.allow on the server and decide whether or not to insert in the shared database or not. An application that uses Cordova will use the same database as your web version.
Assumptions
You don't have the packages autopublish or insecure in your app.

Android: work with Parse database for an IncrementKey column at Parse

I am working on a Android app and is using Parse Database, and would like to add a IncrementKey function such that when a new image is added to the database, the image_id column would increase itself by 1.
Reference: https://www.parse.com/questions/incrementkey
Question:
However, googled for a long while, there are no explicit example to show how to get it work... it involves cloud code at parse. Would there be any hints on how could that be done?
Thanks!
To create a beforeSave trigger for Image (replace where relevant, I've assumed this is your Class that holds the images and counter column - these are properties of the same Object)
file: ./cloud_code/cloud/main.js or a filepath required by main.js
Parse.Cloud.beforeSave("Image", function(request, response) {
//check if this is a new or existing Image
if (!request.object.isNew()) {
//image exists, save as normal
response.success();
} else {
//find the last image saved
var checkImage = Parse.Object.extend("Image");
var imagesQuery = new Parse.Query(checkImage);
imagesQuery.select("image_id"); //save memory by only requesting image_id
imagesQuery.descending("image_id"); //sort, make sure image_id is a Number
imagesQuery.first().then(
function(lastImage) {
//increase the id by 1
var newId = lastImage.get("image_id") + 1;
//save the current object with the new id
request.object.set("image_id", newId);
response.success(); //this saves your request.object
},
function (error)
response.error(error);
}
);
}
});
Resources
Cloud code guide: https://parse.com/docs/cloudcode/guide
Cloud code beforeSave modify: https://parse.com/docs/cloudcode/guide#cloud-code-modifying-objects-on-save
Retrieving objects: https://www.parse.com/docs/js_guide#objects-retrieving
Increment (updating an existing field): https://parse.com/docs/js/guide#objects-counters
See also Parse cloudcode beforeSave obtain pre-updated object (the other way around)
Read the Cloud code guide to learn how to e.g. install the CLI tools to deploy your Cloud Code and check the Cloud logs for debugging.
Disclaimer: code above is untested but based on working functions
Note: use isNew() in a beforeSave handler, existed in an afterSave handler. There's a reported bug for existed in Parse Cloud Code versions 1.6.* - see Parse request.object.existed() return false

Android: Using server-side when working with Parse

Me and my friend are working on an app., and we wish to use Parse.com as our data base from which we can retrieve info.
We can't decide what is the best way to access the data on Parse. For the sake of the example, our app. (i.e. client side) needs something stored on the Parse data base (say some number) - should it directly run the query using the Parse API, or should it make a request to a server side, let it retrieve that number from Parse, and send it back to the client?
We know there's no definite answer, but we couldn't find answer regarding this specific situation. We read this post: When to use client-side or server-side?,
but this not exactly the same case.
I claim that we should try to seperate as much as possible from client side and data bases, and leave these queries run by someone who's in charge (server), where my friend claims this adds unnecessary complication, since it's very natural to use the tools supplied by Parse to access the data base from the client side, without the need for a protocol etc.
We'd appriciate any advice,
Thank you.
In general, go right ahead and make a normal call.
I'd encourage you to do that first in any case, to get everything working on both ends.
Then if necessary go to Cloud Code.
If you are going to do more than one platform (ie iOS and Android), cloud code can be a huge timesaver.
BUT don't forget that for simple calls, cloud code is a waste of time. "Normal" Parse calls are amazingly, incredibly, amazingly, fast and quick to work with.
There is absolutely nothing "wrong" with using normal Parse calls - so do that.
Regarding the question, when do you literally have to use a cloud code call -- you'll know, because you won't be able to do it with a normal call :)
Don't forget very often you can simply use "afterSave" or "beforeSave" in cloud code, to do a huge amount of work. You often don't literally need to go to a "custom call" in cloud code.
Here's a fantastic
Rule of thumb for Parse cloud code --------->
If you have to do "more than one thing" ... in that case you will likely have to make it a cloud code function. If you have to do "three or more things" then DEFINITELY make it a cloud code function.
That's a good rule of thumb.
(Again, as I say, often just an "afterSave" or similar works brilliantly...rather than literally writing a full custom call.)
Here's a typical example of a cloud call that saves 18 billion lines of code in all the platforms covered by the dotcom. First the cloud code...
Parse.Cloud.define("clientRequestHandleInvite", function(request, response)
{
// called from the client, to accept an invite from invitorPerson
var thisUserObj = request.user;
var invitorPersonId = request.params.invitorPersonId;
var theMode = request.params.theMode;
// theMode is likely "accept" or "ignore"
console.log( "clientRequestAcceptInvite called.... invitorPersonId " + invitorPersonId + " By user: " + thisUserObj.id );
console.log( "clientRequestAcceptInvite called.... theMode is " + theMode );
if ( invitorPersonId == undefined || invitorPersonId == "" )
{
response.error("Problem in clientRequestAcceptInvite, 'invitorPersonId' missing or blank?");
return;
}
var query = new Parse.Query(Parse.User);
query.get(
invitorPersonId,
{
success: function(theInvitorPersonObject)
{
console.log("clientRequestFriendRemove ... internal I got the userObj ...('no response' mode)");
if ( theMode == "accept" )
{
createOneNewHaf( thisUserObj, theInvitorPersonObject );
createOneNewHaf( theInvitorPersonObject, thisUserObj );
}
// in both cases "accept" or "ignore", delete the invite in question:
// and on top of that you have to do it both ways
deleteFromInvites( theInvitorPersonObject, thisUserObj );
deleteFromInvites( thisUserObj, theInvitorPersonObject );
// (those further functions exist in the cloud code)
// for now we'll just go with the trick of LETTING THOSE RUN
// so DO NOT this ........... response.success( "removal attempt underway" );
// it's a huge problem with Parse that (so far, 2014) is poorly handled:
// READ THIS:
// parse.com/questions/can-i-use-a-cloud-code-function-within-another-cloud-code-function
},
error: function(object,error)
{
console.log("clientRequestAcceptInvite ... internal unusual failure: " + error.code + " " + error.message);
response.error("Problem, internal problem?");
return;
}
}
);
}
);
If you are new to Parse it's incredibly hard to figure out how to call these from Android or iOS! Here's that one being called from Android ...
this will save you a day of messing about with HashMaps :)
private static void handleInvite( ParseUser invitor, final boolean accepted )
{
String invitorId = invitor.getObjectId();
// you must SEND IDs, NOT PARSEUSER OBJECTS to cloud code. Sucks!
String cloudKode;
cloudKode = (accepted? "accept" : "ignore");
HashMap<String, Object> dict = new HashMap<String, Object>();
dict.put( "invitorPersonId", invitorId );
dict.put( "theMode", cloudKode );
Toast.makeText(State.mainContext, "contacting...", Toast.LENGTH_SHORT).show();
ParseCloud.callFunctionInBackground(
"clientRequestHandleInvite",
dict,
new FunctionCallback<Object>()
{
#Override
public void done(Object s, ParseException e)
{
Toast.makeText(State.mainContext, "blah", Toast.LENGTH_SHORT).show();
// be careful with handling the exception on return...
}
});
}
And here's the same cloud call from iOS ... well for now, until you have to do it in SWIFT
-(void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
int thisRow = indexPath.row;
PFUser *delFriend = [self.theFriends objectAtIndex:thisRow];
NSLog(#"you wish to delete .. %#", [delFriend fullName] );
// note, this cloud call is happily is set and forget
// there's no return either way. life's like that sometimes
[PFCloud callFunctionInBackground:#"clientRequestFriendRemove"
withParameters:#{
#"removeThisFriendId":delFriend.objectId
}
block:^(NSString *serverResult, NSError *error)
{
if (!error)
{
NSLog(#"ok, Return (string) %#", serverResult);
}
}];
[self back]; // that simple
}
Note For the iOS/Swift experience, click to: How to make this Parse.com cloud code call? which includes comments from the Parse.com team. Hope it saves someone some typing, cheers

Need to pass a variable to remote swf

I am working on a prototype Air for Android application that loads some remote swf files (all created and controlled by me) and I need to be able to pass a variable along to the remote SWF.
Here is a quick break down of how the process currently works:
The Android app, called Loader, is installed on the device.
Loader points to my server and finds Player.swf, which it loads into the main stage. Player.swf show a login screen.
When a user logs in correctly, Player.swf receives an XML response from an API with a list of remote SWF videos to display for the user. Player.swf loops through the XML list and plays each remote SWF, one after the other.
Now, so far, so good. The remote SWF videos load up and play perfectly. But I need to start picking up variables from Player.swf (pulled from the XML response) to use in the remote SWF (things like text strings, user ID's etc)
From all the searching I have done, I believe it is down to the Sandbox environment, as Loader is a compiled application and Player.swf + the remote SWF's are all coming off a server. However, now I am wondering, as Player.swf is the one that has the AS3 code to deal with the XML response, and that is located on the same server as the remote SWF's that are played (and therefore should be the same sandbox?)
I was able to pass a variable along using a URL parameter, but it only works locally and not when I use the Android application.
I found an old blog pot about Sandbox Bridges, but the example file download doesn't work anymore.
Can anyone point me in the right direction in using the parentSandboxBridge function/class to pass along a variable (all examples I have seen deal with passing functions and/or are coded for Flex)
I cannot post any code, as I simply have nothing to show for what I want to achieve (I'm totally stumped on this bit!)
EDIT: I managed to get parameters to pass along (even though it worked locally before, it didnt work with the Loader app > Remote Player > Remote SWF animation combo)
I had to set the application domain context inside Player.swf (seeing as it is on the same server as the remote swf animations, not sure why I needed to do this)
But oddly, I cannot use parent or root to pickup variables?
I've tested this on HTC Desire running android 2.2.2 and it works what I've put in comment thus the answer is as follows:)
your host needs to define similar:
var params:URLVariables = new URLVariables();
params["string"] = "ala ma kota";
params["number"] = 1979;
var request:URLRequest = new URLRequest();
request.data = params;
request.url = "urlVarsReader.swf";
var loader:Loader = new Loader();
loader.load(request);
addChild(loader);
then loaded content (here urlVarsReader.swf) can read them as follows:
var output:TextField = new TextField();
addChild(output);
output.border = true;
output.width = 320;
output.height = 240;
output.wordWrap = true;
output.multiline = true;
var p:Object = getParams(this.loaderInfo);
for (var name:String in p)
{
output.appendText(name + " = " + p[name] + "\n");
}
I have a wrapper method for reading params:
public function getParams(li:LoaderInfo):Object
{
try
{
var params:Object = li.parameters;
var pairs:Object = {};
var key:String;
for(key in params)
{
pairs[key] = String(params[key]);
}
}
catch(e:Error)
{
return {error:e.getStackTrace()};
}
return pairs;
}
best regards
EDIT:
This works only with local content fails with SecurytyError e.g. SecurityError: Error #2070: Security sandbox violation: caller http://example.com/urlVarsReader.swf?string=ala%20ma%20kota&number=1979 cannot access Stage owned by app:/loadwithparams.swf

Categories

Resources