I'm making a game of Tetris on android as a project for school and right now im using shared preferences in order to save the current state of the game so that it can be resumed on a later time , i've come to realize that when you store over 100 or so preferences the sharedprefernces object starts working in a strange way , i can save everything but when i try to call the editor to clear (e.clear + e.commit) it wont remove the preferences.
i would appreciate any help regarding this issue
thanks
SharedPreferences are good and lightweight mechanism how to persist data.
But i think for game it's not a win at all. SharedPreferences are usually used for persisting non-structured data for example if you have some application that requires login and when User is logged in successfully you can save this state to SharedPreferences and in next Activities just check it whether User is logged in or not. But in the game you have (i guess for sure) structured data-structures (for instance players and their properties (values) like reached score, loses, wins etc.).
So i suggest you to think about another mechanism for data persisting. Specifically try to think about a possibility to use classic object serializing or and usage of SQLiteDatabase which provide more complex solution how to persist structured data.
A main advantage is that you can persist (serialize) whole objects and then simply deserialize them (and not persist them as specific "chunks" in SharedPreferences). Regarding to SQLite, it provides almost same solution as classic serializing but objects are represented as tables in database.
If you need to remove specific values use this:
SharedPreferences.Editor.remove() followed by commit()
To remove them all SharedPreferences.Editor.clear() followed by a commit()
(references here https://stackoverflow.com/a/3687333/1584654).
However If the values remain limitated, for Shared Preferences should not be an issue.
Related
I'm working on an android cooking app (using java) and the homepage has a recycler view populated with recipes which users can like (similar to FaceBook posts). The like button is a checkbox, what is the best way to save the state of the like checkbox for every recipe, so when the user signs out of the app and sign in again they will not like the same recipe more than one time.
Is using SharedPreference a good idea in this situation?
**im using MySql as a database and firebase is not used.
You could definitely do it using SharedPreferences - but I believe this is more ideally designed for 'preferences' of an application rather than 'application' behaviour state.
You might want to have a look at : https://developer.android.com/topic/libraries/architecture/saving-states?authuser=1
Here you will see some options of how to serialize and persist UI states to memory. I have not actually used something like this before - in the past only using SharedPreferences.
You could of course also create your own storage method, or solution but why bother when ones already exist.
Since you are already using a MySQL database, your application is already grabbing the rows from the DB to show them, so why not add another column called 'checked' which is a boolean type. Then when you get your recipes you get the 'checked' variable, and if it is true, then set your UI state of the checkbox to checked, otherwise false :)
The benefit of this approach is that if your app became 'hybrid' and you wanted a website for it too - the data on the database becomes centralised, meaning your persisted user state is the same on mobile as it is web experience, which is a nice benefit!
I'm trying to save a stack of objects, so that the stack will still be there when I close and then reopen the app.
I tried extending Application to create a global variable, but that is deleted when the app closes. I think I should be using Java's internal memory, but don't know how to do so with a stack and not a single object. I am having trouble researching this, as whenever I look for anything with "stack" in the search, everything is about the runtime stack, not the data structure.
Best way to store large data objects is internal SQLite database with help of Room, OrmLiite or other wrapper.
Or if it small values like saved options, time or similar then use SharedPreferences storage
The object needs to be serialisable. For this you need to extend your object with Serializable
https://developer.android.com/reference/java/io/Serializable
You need to store the object to the disk in the form of a file or in a database as a blob.
When you start your application you need to deserialize the object and load it into memory.
There is an alternative to the above 3 points though.
There is an open source library called SnappyDb which can persist key value pairs and do serialization and drserialization pretty fast.
https://github.com/nhachicha/SnappyDB
you need to use sharedPreferences.
i will show you how to save an string and use it .
step1 : SharedPreferences sharedPreferences;
step2 : sharedPreferences= this.getSharedPreferences("ur choosen name",0);
step3 : sharedPreferences.getString("mystring","");
step4 :`sharedPreferences.edit.PutString("mystring","what i want
save").commit();`
now its saved
step5 : String mystring;
step6 : mystring = sharedPreferences.getString("mystring","");
use step 5 and 6 for using your saved variable
In my android *project* I have to keep track of product details of certain number of products. All the data on these products are store in a SQLite database. I can use select and update in SQLite to perform keep track of product objects. So I can store product details when ever they are changed.
Also I can load all the products into a hash map or such a data structure at the beginning and keep track of those product objects.
what matters to me is out of above both which one is more efficient and productive. Can someone help me. Thank you!
This depends on the number of products. A HashMap resides in RAM, a database resides on the disk.
This also depends on the number of queries per second and the nature of the queries. Database developers have put a lot of effort to support indexing and filtering; if you need that, reuse is better than re-inventing.
Whatever approach you choose, you must remember that an Android application process may be killed at any moment (e.g. when memory is needed for another process), and your code is guaranteed only to receive onPause() (and not onDestroy() or onStop(), see the activity life cycle). If necessary, the application will be restarted later, but all data kept in RAM (and not saved) will be of course lost. Therefore, in either onPause() or in onSaveInstanceState() (what bundles are for) you must save the application state. In your case this may mean having to save the HashMap and all auxiliary data structures.
OTOH, if the number of products is small (and is expected to remain small), a database can be an overkill; if you just need to choose one of 10 items, writing a loop is faster than doing all the database support.
One more important note: an Activity is a Controller from the MVC viewpoint (and as to the View, you usually create and XML and reuse the existing framework classes, although you could program custom controls). An Activity is re-created each time the device orientation changes and in some other cases. But your data belong to the Model part. They must survive the orientation change. So they must not be owned by an Activity.
To answer
a. HashMap will no doubt win over sqlite in terms of memory operations, hence it will run faster. But it will not provide you consistency, Mobile being a volatile environment, OS is bound to kill an application in background, or in foreground if its memory requirement are not met, in such scenarios you might loose all the important updates made before committing it to a permanent storage.
b. SQLITE is slow compared to Map, but is reliable it will make sure all the commits to your data is saved properly, even though app crashes db will guarantee to restore data you committed before that, Map certainly lacks this functionality.
c. Considering a Scenario when you have loaded data into a MAP to enable faster operation and performing sync with database whenever you record any delta to your data, this scenario is very plausible and can perform excellently if designed properly.
To conclude, You should proceed with DB + MAp operation, this will make your app running smooth if there is lots of database operation involved, just need to make sure keep data + app seperate to eleborate dont make your app dependant on loading of data initially.
I have a program with a main activity which spawns 4 different intents with lists in each. There is a database used to track all of the choices from these lists. Currently with the way that startActivityForResult() works I am having the program send back a comma delimited string which is saved in an array in the main activity and upon main 'submit' it is all saved to the database. The lists represent choices made on a per-day basis but each list corresponds to the same day. I am using putExtra() to send the correct list to the activity.
This can be an issue if the user closes the program or android kills the app the array may be lost. I want to update the current dates data from each spawned intent but when I would do this it would create a new entry.
Main question: Can I set a global date value (that the user sets in main) that each intent can reference to use update for my sql statements. I want to make sure that there is no loss in data. Currently writing to the database is only done in the main activity upon submit but I would like to have the app write to the db from each intent.
This question is very abstract in my brain and if there is a need to clarify I will do my best. (I am at school and just brain storming things to try when I get home)
Write the array to Shared Preferences in onPause() and onTerminate(). You can use the array element number as the key and whatever is in that array element as the value.
I can't quite work out where you're going with the global date/time stamp, but if the point is to prevent data loss, Shared Prefs can be damned handy.
I am planning on creating an android application sometime in the future in which I'll want it to display a lot of constant data on the screen.
I'm not sure the best way to do this but I see two options:
Storing the data within the code itself such as creating a constants class.
Using an embedded database to hold the data.
I'm guessing option #2 is the best way? But it just seems weird using a database if I'm not going to be doing any updating to the database, I would only be selecting.
The total amount of data that I need the application to display is maybe about 400 lines consisting of a string and two integers...
Is there a different way people use for such a situation that I don't know about?
But it just seems weird using a database if I'm not going to be doing
any updating to the database
I am totally disagree with you. Database is not only for updating. It can be used as a better storage and definitely a best way for searching. So as you want to preserve the data then it is definitely wise to use database.
But if you want to handle data which will not persists , i,e you will use different datas for different run then you can use temporary class or other data structure to store data.
Finally, If you are planning to have portability then File storage is an easier solution.
SO you can see, that it totally depends on what you want.