Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Welcome everyone!
I'm programming a mobile game on Anroid.
I really want to know how to save Player Data.
It will be a game that can be run on different devices without loss of data.
Using SharedPreferences
Using JSONObject, JSONArray and save it into file in Internal Storage and upload it to the external server
SQLite, MySQL
What would you choose? What are the pros and cons of each option?
I would like to save data for example:
Highscore
Life
Mana
Count of steps
Level of character
Amount of money
and more...
SharedPreferences should be the way to go for such a small amount of data. There are many benefits to using them over SQLite in this example.
I would discourage using external server because I personally would not like my game to require internet for playing.
It depends on how much player data there will be. But unless there is a lot of player data, I would suggest using shared preferences, especially if there is something simple like a Player object, or a list of Player objects. that will cover it.
You could use something like the following for a list of Players, and change any reference to that list to just a Player object if you only want to save 1. If you have a lot of data, players, or would need extra security you may want to go with SQLLite.
public class PlayerPrefs {
private static final String PLAYERS_PREF_FILE = "PLAYERS_PREF_FILE";
private static final String PLAYERS = "PLAYERS";
private static SharedPreferences getPrefs(){
final Context context = ApplicationData.getAppContext();
return context.getSharedPreferences(PLAYERS_PREF_FILE, Context.MODE_PRIVATE);
}
public static List<Player> getPlayers() {
final Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Player>>() {}.getType();
SharedPreferences prefs = getPrefs();
String players = prefs.getString(PLAYERS, null);
if (players == null){
return new ArrayList<Player>();
}
return gson.fromJson(players, listType);
}
public static void setPlayers(List<Player> players) {
final Gson gson = new Gson();
if (players != null) {
final SharedPreferences prefs = getPrefs();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PLAYERS, gson.toJson(players));
editor.apply();
}
}
}
Also, you'll need to include the following in your Gradle file:
compile 'com.google.code.gson:gson:2.5'
Related
In my Android app i archive large amount of data as json in my SharedPreferences, the json items are build as the following {"codiceArticolo":"0401100028053","data":"mer 03/07/2019","qta":"1"} there could be more than 500 items like this in the JSON.
Actually the json is generated from an ArrayList from the following method
public void saveStorico(){
ArrayList<ItemModel> itemToRemove = new ArrayList<>();
ArrayList<ItemModel> itemToAdd = new ArrayList<>();
// various controlls
for(ItemModel itemModels : itemModel){
boolean exist = false;
for(ItemModel itemModel2 : itemStorico){
if(itemModels.getCodiceArticolo().contains(itemModel2.getCodiceArticolo())) {
itemToRemove.add(itemModel2);
itemToAdd.add(itemModels);
exist = true;
}
}
if(!exist) {
itemToAdd.add(itemModels);
}
}
itemStorico.removeAll(itemToRemove);
itemStorico.addAll(itemToAdd);
SharedPreferences sharedPreferences = getSharedPreferences("STORICO_ORDINI", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(itemStorico);
editor.putString("storico", json);
editor.apply();
}
But i'm having some issues when i fetch that data it seems that some of saved items just are not being saved, could there be a max lenght limit that i could save inside sharedpreferences as json?
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
For large amounts of data as in your case, SharedPreferences is not a good choice.
You should rather be using a SQL database or a NoSQL database instead.
As per what I have seen before, if the shared preferences go beyond 100kb, you need to consider alternatives. And if it exceeds ~1MB, there potentially can be out of memory exceptions.
This question already has answers here:
Append more values to Shared Preferences rather than overwriting the existing values
(3 answers)
Closed 5 years ago.
I want to store notifications received from Firebase in my android app. I am using SharedPreferences for that. The problem is when I send notification more then 1 time it overwrites the previous one.
String[] notif={"","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};
ListAdapter yo = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notif);
ListView yup = findViewById(R.id.list1);
yup.setAdapter(yo);
SharedPreferences sharedPref = getSharedPreferences("notification", Context.MODE_PRIVATE);
String y = sharedPref.getString("notify","");
notif[1]=y;
just create another class AppCache. In which you have to do all sharedPreference related work like storing/retrieving the data from/into sharedPreference. Here is the class
public class AppCache {
private static final String PREF = "notificationApp";
private static final String COUNT_KEY = "count_key";
public static void saveNotification(Context context, String notification) {
SharedPreferences sharedPref = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
int count = sharedPref.getInt(COUNT_KEY , 0);
count++;
sharedPref.edit().putString("notification"+count, notification).apply();
//saving count in prefs
sharedPref.edit().putInt(COUNT_KEY , count).apply();
}
}
1 -> In SharedPreferences create another integer for count that will hold the number of notifications in sharedPreferences.
2 -> While saving the notification in sharedpreference, use a unique key for every notification,for example you can use a combination of any string and the count which you declared before like "notification"+(count++). count++ will create a new key for every new notification.
3 -> Now you can retrieve all notification by using count.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making an app that my wife can use to check if a certain IC friendly or not. The problem is that I need 5 columns if you will (foodName, safe, try, avoid, foodCategory. Each may or may not have a description of the food name under safe, try, avoid. Should I use a database an .xls file or can I do it in xml?
It depends on your requirement/ useage
use sharedPreferences or sqlite database
if you want to store data for long term use sqlite
and if you want to maintain sessions use SharedPreferences.
SharedPreference
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value. and it requires API 11
}
And for using Sqlite #Sri Hari have shown you an example..
Create a new SQLite database and store it. her you can store multiple tables safely.
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
For storing data in android you can use:
Shared Preferences - Store private primitive data in key-value pairs
Internal Storage - Store private data on the device memory
External Storage - Store public data on the shared external storage
SQLite Databases - Store structured data in a private database
Network Connection - Store data on the web with your own network
server.
IMO for your purposes the most efficient option can be Shared Prefeerences or SQLite Database
More details for storing data you can find here.
Please note that you can look also for some ORMs to make it easier with SQLite Database - GreenDAO, OrmLite,...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to add a dynamic textview to the page when I click OK in the dialog box. My problem is that I want that textview to be visible even when the app is opened again.
P.S. I can add multiple textviews(1 at a time) and all should be visible on opening app again. Example : Creating a new Playlist and the new playlist name appears always . Can anyone guide me how to do this?
You can store info about added TextView-s in SharedPreferences and when app is opened again get this info from SharedPreferences by getStringSet for example (to get added TextView's key names) and by other methods and create new TextView-s and add them to an activity layout.
ADDITION:
The most universal approach to this task is to save JSONArray which contains TextView-s data in SharedPreferences as a string by using toString() method and when app is opened again read JSONArray from SharedPreferences as a string and fill data of newly created TextView-s.
EXAMPLE:
private JSONArray data;
...
SharedPreferences pref = getSharedPreferences("application", 0);
data = new JSONArray( pref.getString("text_views_data", null) );
List<TextView> tvList = new ArrayList<TextView>();
for (int i = 0; i < data.length(); i++){
JSONObject ob = data.get(i);
TextView tv = new TextView(this);
tv.setText( ob.getString("text") );
tvList.add(tv);
}
...
private saveTextViewData(TextView tv){
JSONObject ob = new JSONObject();
ob.put("text", tv.getText());
data.put(ob);
SharedPreferences preferences = getSharedPreferences("application", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("text_views_data", data.toString() );
editor.commit();
}
You should call saveTextViewData method when you add new TextView.
you can store each the TextView as an object in an array of objects. Then you can save this array in a SharedPreferences then when you open the application get the array from SharedPreferences and add the TextViews to the application dynamically.
This is a simple solution!
I have my own Objects which I need to store for later use. The User saves this object, it is turned into a JSON String, then when the User is connected to a network, the JSON String is turned back into the object operations are performed on it.
My problem is that, at run time, how do I know how to store the object?
i.e
Gson gson= new Gson();
String pointOfInterest = gson.toJson(point);
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit();
sharedprefEditor.putString(?KEY?,pointOfInterest);
What can I use for the value of KEY? If I use an index, it will get reset every time I open or close the app, and this will replace my Objects.
Edit
Sorry I didn't make this clear enough, the method that the above code is in can be run an arbitrary number of times and there could be several pointsOfInterest to store.
First of all, if you use an index, the Preference will stay forever:
For instance:
sharedprefEditor.putString("JSON569",pointOfInterest);
You can also save the index in an other preference; for instance separated by a column:
sharedprefEditor.putString("indexes","569;789;852");
You can, easily check if an instance exists:
myPreference.getString("JSON789","").contentEquals("");
Or get all your instances:
for (int anIndex:indexes)
Log.i("TAG","Current value: "+myPreference.getString("JSON"+anIndex,""));
Please xplain a little bit more your question, I see no difficulties there/
You can name the key whatever you want, just make it consistent. One way to do it is make a constant in your class for it:
public class MyClass {
private static final String OBJECT_KEY = "myObjectKey";
...
Then when you save your object:
Gson gson= new Gson();
String pointOfInterest = gson.toJson(point);
SharedPreferences.Editor sharedprefEditor = application_shared_preferences.edit();
sharedprefEditor.putString(OBJECT_KEY,pointOfInterest);
When you load it, just use OBJECT_KEY to get a string out of the shared preferences:
String objectString = sharedPrefs.getString( OBJECT_KEY, "" );