This question is about Parse
From what I've found,
Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want.
However as a learner, I got multiple questions :
Can I set my own objectID while saving data?
Does the objectID varies when pushed from different devices? If so, how to retrieve those data?
Can I set my own objectID while saving data?
yes you can
ParseObject parseObject = new ParseObject("<ClassName>");
parseObject.setObjectId("<ObjectId>");
Does the objectID varies when pushed from different devices?
every object has unique ID even if they created by the same device.
Related
I am doing a simple application where a ListView is populated from the data stored in SharedPreferences. I need to read all the key pair values from SharedPreference. I used the code given in another post with same question, but it has not helped me at all.
The code is using a Map to getALL() from SharedPreference. When I try to print the count() of keys in the MAP it is always giving zero count. I am stuck in my application building due to this problem.
Can somebody help me with a simple code to retrieve all the key and values from a SharedPreference? Thanks.
You can store and retrive arraylist or array data like this Example.
You are fetching data into list but you are not storing data into sharedprefence from arraylist.
In this situation(never tried but this may work)
Store
retrive size variable as in above example
increament size by 1(to store one value)
store value in SharedPreference
Store size in SharedPreference.
Fetch
retrive size variable as in above example
then go through loop for all values
Suppose Type is the name of the array which contains A,B,C,D as elements and is created in strings.xml.Now in the form user can either select any of the elements or add new elements.Suppose user adds E,F,G .Now what i want to achieve is that anyhow the Type array have A,B,C,D,E,F,G in it. Using sqlite is done.But i want to save it in the Type array only and not anywhere else.Is it possible ?
Since anything that you define in res folder acquires a unique id in R.java, which is an array, and size of array cannot be changed at runtime.. So, it is not possible.
You can only save data to persistent storage like SQLite data base, shared preferences or a text file, each of which have different strengths and weaknesses and are suited for different situations, so take your pick.
can i store two or more values with same key using SharedPreferences in android? If no, please tell me how to store values of username, first name, password etc when many users register in registration app?
Ex:
person A registered with username="john12", first name="john" and DOB="06/06/2000".
person B registered with username="arun89", first name="arun" and DOB="08/11/1989".
Now, I want to store these values in SharedPreferences and retrieve them later. Is it possible using SharedPreferences? If not, Please tell me how to do in other way.
Thank you in advance.
I woud consider creating a JSONObject and add the fields you want to store as a key:value pair.
json.putString(key, value);
You can then store the json object in it's string representation with json.toString() and restore it later with
JSONObject jo = new JSONObject(jsonString);
String value = jo.getString(key);
JSONObject also offeres different data types beside strings.
It really depends on how much data you want to store. Depending on that I would choose SharedPreferences or a SQLite implementation.
You cannot store these values directly (as ones added latter will overwrite previously added) but you can always store Parcelable and put your data into it
For your case it is better use SQLIte database.But if you want to use shared preference it is still possible.You have to use a key with additional index to remember different user like
UserName1:arun
UserName2:john
You have to remember the total number of user.Then can maintain all of them.you can also use other data structure like hashmap to maintain data for the shared preference.
I dont't think it is possible, as you don't know the number of users.
You could try to separate the users with commas, but that's lame.
You should consider using SQLite database.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Then you have to store a array List of user objects first create a class userInfo then create a array List type of userInfo then store the data in this list and put a serialize-able object in SharedPreferences.
You can also store them on a single key called "registers" as string. Concatenate each register to preference. Put ";" (or any other characther you want) between each register. Then parse the string and use the values.
Key: registers
Value: "username=john12, first name=john, DOB=06/06/2000;username=mike12, first name=mike, DOB=06/07/2012"
Using split method of String will give you a list of registers as String.
registers.split(";");
Splitting again with "," will give you properties of each register.
I am trying to implement a data structure which allows me to keep track of an index (so I can blindly access the data points), a key (which needs to be there to identify the data in the rest of the program), and a value.
I've looked at a map, but that does not allow me to access the data points without any key. I need some combination of a Queue and a Map. Does this exist and I'm just missing it? Thanks for the help.
I believe what you are looking for is a LinkedHashMap. It will return an ordered collection and you can access values via a key.
LinkedHashMap<Key, Value> myMap = new LinkedHashMap<Key, Value>();
myMap.put(aKey, aValue); //adds to map.
myMap.values(); //returns collection of values
aValue = myMap.get(Key); //returns a value with the given key
I'm unsure how I'm supposed to save the game state of my game that I'm developing. Should I save a instance/object containing all the game information? If yes, how? Or should I save all the relative information in a .txt file and save/load information when needed?
How do you do this and what do you think of my proposals?
You can't save an Instance / Object unless you serialize it and save it to some text/binary/database file. Your two options are kind of identical therefore.
What you need to save is all information that you need to reconstruct your game state. There are probably some information that you can derive from here.
If you have just a small fixed set of variables that define your gamestate then use SharedPreferences.
If you want to keep more than one state and / or it is more complex to save use some text (xml, json, ...)/binary/database/.. representation and store that.
I can suggest to use Parse.
https://parse.com/docs/android_guide#objects
The ParseObject
Storing data on Parse is built around the ParseObject. Each ParseObject contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each ParseObject. You simply set whatever key-value pairs you want, and our backend will store it.
For example, let's say you're tracking high scores for a game. A single ParseObject could contain:
score: 1337, playerName: "Sean Plott", cheatMode: false
Keys must be alphanumeric strings. Values can be strings, numbers, booleans, or even arrays and objects - anything that can be JSON-encoded.
Each ParseObject has a class name that you can use to distinguish different sorts of data. For example, we could call the high score object a GameScore. We recommend that you NameYourClassesLikeThis and nameYourKeysLikeThis, just to keep your code looking pretty.
Saving Objects
Let's say you want to save the GameScore described above to the server. The interface is similar to a Map, plus the save method:
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
try {
gameScore.save();
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
After this code runs, you will probably be wondering if anything really happened. To make sure the data was saved, you can look at the Data Browser in your app on Parse. You should see something like this:
objectId: "xWMyZ4YEGZ", score: 1337, playerName: "Sean Plott", cheatMode: false,
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"
There are two things to note here. You didn't have to configure or set up a new Class called GameScore before running this code. Your Parse app lazily creates this Class for you when it first encounters it.
There are also a few fields you don't need to specify that are provided as a convenience. objectId is a unique identifier for each saved object. createdAt and updatedAt represent the time that each object was created and last modified on the server. Each of these fields is filled in by the server, so they don't exist on a ParseObject until a save operation has completed.
Retrieving Objects
Saving data to the cloud is fun, but it's even more fun to get that data out again. If you have the objectId, you can retrieve the whole ParseObject using a ParseQuery:
ParseQuery query = new ParseQuery("GameScore");
ParseObject gameScore;
try {
gameScore = query.get("xWMyZ4YEGZ");
} catch (ParseException e) {
// e.getMessage() will have information on the error.
}
To get the values out of the ParseObject, there's a getX method for each data type:
int score = gameScore.getInt("score");
String playerName = gameScore.getString("playerName");
boolean cheatMode = gameScore.getBoolean("cheatMode");
If you don't know what type of data you're getting out, you can call get(key), but then you probably have to cast it right away anyways. In most situations you should use the typed accessors like getString.
The three special values have their own accessors:
String objectId = gameScore.getObjectId();
Date updatedAt = gameScore.getUpdatedAt();
Date createdAt = gameScore.getCreatedAt();
If you need to refresh an object you already have with the latest data that is on the server, you can call the refresh method like so:
myObject.refresh();
You could use an SQLite database to save the important variables in your game. If the game is started from one class you could provide that class with two constructors, one which instantiates a normal game from the beginning and another which accepts all of the variables from your game and creates the game object from the save point.
This will allow you to have more than one game save (by saving the id along with any data) and game saves will not be lost if you ever update your game (Assuming you don't alter the database).
Do a quick search for "constructor overloading" to find out more.
If your game is not data intensive and if serializing and saving to Shared Preferences is enough, you can check out the GNStateManager component of the library I wrote to make it easy to store and retrieve the required fields of the activity marked my #GNState annotation. It is dead simple to use. Other singleton class object states can be saved too. See here for Setup and Usage information: https://github.com/noxiouswinter/gnlib_android/wiki/gnstatemanager