I am building a monopoly game and from what I'm doing I'm almost done, but I want the game to end after 30dice rolls. But the way I want to do it is weird. I need a way to store data and check if the data is upto 30 or not, I mean check the amount of data is a row, I've been looking if sqlite or shared preferences would do, but can't get anything. Any idea would be welcomed and if you can help review my code too, I wouldn't mind. Thank You.
If you realy want to persist it in the Database, you want to have a key-value table current_game_progress with an item dice_rolls and update this each dice roll.
UPDATE current_game_progress SET content = content + 1 WHERE keyname = "dice_rolls"
But its a bit overhead. Maybe you want to store it local in a variable and transfer it on "save" action to the database.
Related
I've made a little android game and I have a problem saving the overall score which should be retrieved every time the app starts up again instead of just starting at the default 0 like it always does.
I looked at SharedPreferences but that seems to be more about saving high scores that won't change.
Is there a way for my save the a score which will be changed as more games are played?
I assume I'd need to do the following:
Retrieve the saved score
Put it into a variable
Change that variable
Save it again end of game or every-time it changes (depending on whether or not it affects performance)
Edit: Turns out SharedPreferences would work for this scenario. Now could someone please provide an answer of how to implement it?
I believe you can use Shared Preference for that purpose.
It can be used to save your score, overwrite the score and retrieve the score.
Shared preference uses the Key value pair.
I'm not sure why you'd come to the conclusion that SharedPreferences would be more suitable for non-changing values.
I think this is an excellent use case for it.
You could try other persistence options (such as integrating SQLite into your app) but this seems like the quickest option with the least amout of overhead.
Still, if you're interested in other options, I hope you've skimmed through the storage options in the Android documentation:
http://developer.android.com/guide/topics/data/data-storage.html
And, of course, using SharedPreferences will have to be done in conjunction with Application LifeCycle methods (such as onResume, onPause, etc):
http://developer.android.com/training/basics/activity-lifecycle/index.html
You can use a SQLite database to save the score value.
To retrieve you current score in the database use this query.
SELECT score from ScoreTable where id = userId;
Assign the retrieve value to a variable.
At the end of the game // Update the score value
int finalScore = initialscore + newScore
UPDATE ScoreTable SET score = finalScore WHERE id = userId
I need to work with a persistent String Array (n Rows, 1 column).
* On first running the app, the String Array needs to be created empty.
* On subsequent app executions the Array will be populated from a File and the contents need to be available throughout the rest of the app.
* As the app is executed, the Array needs to be able to 'grow' in row count
* As the app is executed, the Array rows need to be able to grow in length
* The user will have the option to Clear the Array of previous entries.
* At the end, the String Array contents will be written back to a File.
I find a lot of references to Putting and Getting from an existing SharedPreferences String[] but, in the newness of my Android development, I am struggling with how to proceed.
EDIT Follows...
The data itself suggests using an Array
Example:
MAIN ST. F55 63 KY08:57 12142015--------KY11:24 12142015345TMH KY13:57 12142015
MAIN ST. F56 WYE123 IN08:57 12142015--------KY11:24 12142015--------KY13:57 12142015
1ST ST. F57 --------KY08:57 12142015--------KY11:24 12142015789FPF KY13:57 12142015
1ST ST. F58 456FPF KY08:57 12142015998FPF KY11:24 12142015--------KY13:57 12142015
1ST ST. F59 789TTM KY08:57 12142015--------KY11:24 121420151234DG KY13:57 12142015
I first need to have this data in a File
Then in one GUI I check for the existence of the file.
If one exists, fine
If none exists, I create one.
Then, in subsequent GUI's, I must check for the existence of parameters
If they do not already exist, add them to the existing data lines.
If they already exist, notify the user
And so on and on.
Then when all of the current 'pass' data has been collected via multiple, separate GUI's, I have to write out the whole data-set into the file.
My reason for thinking that I need a SharedPreference approach is the need to find and check data from GUI to GUI as the user progresses through the app.
If that 'belief' is wrong, I am open to better approach suggestions.
EDIT 2 follows....
On further study of web references, I am beginning to think that perhaps the best approach for this data and how the data needs to change might be to use a SQLite approach. Any ideas about this?
Any assistance/suggestions you might have would be greatly appreciated.
i would discourage you from using sharedpreferences for anything else than preferences. means things that change rarely - really rarely and are really lightweight. do not put much data in there. less is better. the data structures underlying sharedpreferences are not a database.
another note. it is not a string list, but it would be a string set. sets are not necessarily ordered, nor do they necessarily keep their order. means - it is not rows. its a collection of strings that can come back in any fun order (usually there is some, but that depends on the implementation which i do not know)
now you could go and make your own list, your own data structure, save it into a string and read it out, use json to do exactly that or something similar, or better - use a database, which would exactly do that.
http://developer.android.com/training/basics/data-storage/databases.html
explains it, but as you'll see its something that might take some time.
now dont get me wrong, but i have to warn you about the following approach. it is valid, but has many problems and is far from thread safe. it will not be a problem as long as you only open it from the ui thread and do not keep anything in memory to cache - if you do it will create lots of problems.
your problem of adding a line and clearing can be solved by using a file. just a simple file
look here
http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
the change is to append when writing:
openFileOutput("filename", Context.MODE_APPEND);
see the context mode? now you can basically just write one line and append every time.
if you wanna clear the file, just deleteFile("filename")
this is as said not threadsafe, but can be a viable option if used carefully.
Please follow this step to achieve what you want with sharedPreference
create the class Parent for SharePreference
Create your empty Array
Convert Your empty array to String and put it on SharedPreference
to call your empty array from sharedPreference
Call your sharedPreference using your key
Convert the String to array
You get your array from the sharePreference
Hope it helps, and maybe this link will help you :
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
You can use my open-source library called prefser, which solves this problem and uses SharedPreferences and Gson under the hood. It's basically wrapper for default Android mechanism.
You can use it in the following way:
Prefser prefser = new Prefser(context); // create Prefser object
prefser.put("key", Arrays.asList("one", "two", "three")); // save array of Strings
String[] value = prefser.get("key", String[].class, new String[]{}); // read array of Strings
For more information check repository of the project, tests and README.md file.
Link: https://github.com/pwittchen/prefser
Please note, SharedPreferences have some limitations and shouldn't be used for storing large amount of data. If you expect a lot of data, consider using SQLite database or another type of database (e.g. with NoSQL or similar approach if you strive for simplicity).
OK, based on the data, how it needs to be manipulated and the pros and cons of using a SharedPreferences approach, I have decided to go with a SQLite approach.
With that approach I should be able to readily check:
* if the necessary table exists (if not create it)
* if the necessary Field1 + Field2 exists (if not create a new record)
* and I will be able to modify the record's Field3 contents as needed
Then when the user's actions are complete I can convert the SQLite table 'records' into strings and write them out as a File and then either DROP or PURGE the associated SQLite table (until needed next time).
I sincerely appreciate all of your suggestions.
Thank you.
I have some scens with and I want save their state of view when app is closed. Some times it's one thing like "is that scene has opened shop window?" but sometimes ther is much more info which I need to store. So is better to use for it UserDefaults/SharedPreferences (json to string) or create model, serialize those info to model then save it to DB?
I will be thankful for Your opinion.
I use SharedPreferences when i have to save a variable, such as UserName, Country of Origin, access token, location, UsersCurrentLevel, UsersCurrentHealth etc.
I use Database when i have data that requires much manipulation or has more specifications to it. Such as questions for users,
video ad's details(seenState , directoryPath, urlToDownloadVideo, hasVideoBeenAlreadyDownloaded etc.), lists of data, etc.
So i would suggest you use a mix depending on the data.if it has a single entry use SharedPreference else if it has a list/ multiple data for a single format put it in a DB. Hope this helps.
I'm making a app that can reserve message from php server and append new message in listView,
then mark a point on that item to show unread,of course it will disappear when click the item,
these is my question:
how can i save the read/unread mark on each item in order to when i login the app next time i
still can see the mark.
I have tried using share preference but it seems not a good solution.there is so may key to save and it's inconvenient when modify the value.
is it need SQLite ? or have easier solution? need some to help.
I have a listview called history that I call every time that I so something significant (ie open or close the app or record some info) The problem I have is that it records things from top to bottom meaning the most recent information is on the bottom of the listview. The second problem I have is that the listview gets deleted after the app is turned off. How do people usually save their history? (ie shared preferences can only store one variable and thats not enough, I would like to save a maximum of 30 entries to the listview)
Thanks
One option I use is to JSON encode my history list and store the resulting string to SharedPreferences. You can then order it as well (simply add items to the List that backs the ListView with new events first) and save it and restore it from the SharedPreferences file.
EDIT: Try something like this:
org.json.JSONArray tracking_users = new org.json.JSONArray();
tracking_users.put("history 1");
tracking_users.put("history 2");
tracking_users.put("history 3");
You could also consider using a database to store the Log of these events, tends to be more efficient.
See one of these for an introduction to android databases