I am trying to save the values of various variables which my game is progressing, like logo number or lives available, etc using LIBGDX framework.
Code goes as such:
static Preferences prefs = Gdx.app.getPreferences("My_state");
public static void ContinuePutstate() {
prefs.putInteger("option", MenuScreen.option);
prefs.putInteger("lifes", Loadassets.lifes);
prefs.putInteger("hammertouch", Loadassets.hammertouch);
prefs.putInteger("multilogonum", Loadmultiple.multilogonum);
prefs.putInteger("brushtouch", Loadassets.brushtouch);
prefs.putInteger("leveluser", Loadassets.Leveluser);
prefs.putInteger("iconnumber", CorrectScreen.iconnumber);
System.out.println("HAd saved option "+prefs.getInteger("option")+" and original option is "+MenuScreen.option);
}
When I tried to print that, I am getting option 0 but menuscreen option actually has another value.
after putting all values use
prefs.flush();
this will write the data to preferences
see
https://code.google.com/p/libgdx/wiki/Preferences#Flushing
It is important to note that creating a singular static instance is the proper way to go with the LibGDX Preferences framework, because the Android OS allows you to obtain only one preferences instance, and not more. Meaning, if you tried to get more preferences than just a single one, the key-value pairs would not be saved.
Related
So what Im trying to achive is: When the user purchases a new item (a texture) they can click a button to replace the old Item(texture) with the new one.
What got in my mind first was Objectmaps. So I created this:
ObjectMap<Integer, Texture> screenMap = new ObjectMap<Integer, Texture>();
Im only using two items at the moment just to get a hang of it:
screenMap.put(prefs.getInteger("stoneOne", 0), sdStone);
screenMap.put(prefs.getInteger("stoneTwo", 1), stone_3);
Here´s the methods I use to change the texture:
public void setStone1() {
stoneImage = new Image(screenMap.get(0));
}
public void setStone(int screenId) {
stoneImage = new Image(screenMap.get(screenId));
}
And now to the part I can figure out:
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("textField", textField.getText());
prefs.putString("textArea", textArea.getText());
prefs.getInteger("stone", );
prefs.putInteger("stone", );
prefs.flush();
I have no Idea what Integer to put in there as you can see I even left it out right now. I tried the screenId integer but it´s not reachable since it is in a void? P.S never mind the weird names I got for things. I took some code from an old project.
Try to walk for another way.
Save Texture to sdcard.
Save path to file into preferences.
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("texture_one_path", "/sdcard/tex1.jpeg");
prefs.putString("texture_two_path", "/sdcard/tex2.jpeg");
Sergey is right. Textures are heavy and big, and you could potentially have tons of them. That's meant for the SD card.
Preferences are lightweight, secure configuration files used on mobile devices. They're usually encrypted, too, so accessing them always has a cost. They're used usually for user settings, login information, etc. The Android extrapolation of Preferences is called SharedPreferences. Here's the doc: http://developer.android.com/reference/android/content/SharedPreferences.html
The iOS concept of "SharedPreferences" is called NSUserDefaults, and here's its page: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Bottom line: you shouldn't be saving much information to the preferences. Use it for strings, global values, user settings (volume level, user credentials, turn off gore, etc.) For large string data, use raws. For large media, use SD card.
Hope that helps.
I'm trying to figure out when to use a saved instance state versus loading information from a shared preferences file. I have two variables that I wish to save, time and score. I want to make sure that if the user returns to the game screen that their score and time is saved and restored regardless if it's from onPause state or onStop.
I have three keys:
public static final String ARG_SCORE = "score";
public static final String ARG_TIME = "time";
public static final String SHARED_PREFS = "shared_preferences";
If the game is paused and a dialog is shown, when the user returns should I do
public void onRestoreInstanceState(Bundle savedInstanceState){
int score = savedInstanceState.getInt(ARG_SCORE);
}
or should I do something like:
protected void onResume(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt(getString(R.string.saved_high_score));
}
Overall, I need help understanding the lifecycle and when to store vital information such as time and score of the game. I simply need to avoid the user having to restart in cases they weren't able to finish the game.
Lastly, I'm assumed that the sharedPrefs saves to an xml file. Is this correct? Does anyone have a sample xml for how my sharedPrefs should appear? Do keys which are saved to bundles of savedInstanceState get stored in xml files as well? If so, any examples? If not, where is the information stored?
THANKS!
edits:
ok cool beans. Thanks! One more question, when defining a key for a key-value pair stored into sharedPreferences such as
public static final String ARG_SCORE = "score";
why is the "score" string stored? When would this ever be used? I've always placed a value into the key_value pair using something like
args.putInt(ARG_TIMER, timerINT);
and retrieved using
scoreINT=savedInstanceState.getInt(ARG_SCORE);
Why is a name needed for the key ARG_SCORE? When would I need the name? Does it have to stay type String?
use saveInstanceState when you are frequently moving back and forth between activities and use SharedPreferences when you want to keep information for long time and yes sharedpreferences stored in an xml file. you can view using DDMS in eclipse.
Remeber, in saveInstanceState, when you close app mean it get removes from memory, information will also lost. And in SharedPreferences, information will remain there if you close your app.
It will depend on how you want to manage the data. Both options (and more) are feasible:
If you want to fill once and keep the data even if the app gets
killed, use SharedPreferences.
If it's volatile data that will have to be reentered differently some
other time (i.e., days later), then use onSavedInstanceState.
If you want to keep multiple datasets on the same device, then use a
SQLiteDatabase
You usually want to use SharedPreferences when you want to persist some information between different app session. Imagine you want to store information that you want to retrieve also after the user closes the app.
SavedInstanceState is used to keep some information while user is using the app and allow you to track temporary state of your activity or fragments.
Hope it helps.
when you press home button then still your activity remains in background. since there is some memory constraints in android , there is always chance some other application can take your memory. so to resume application from same point where we have left we use saveInstanceState.
we use sharedprefrence when we have to save small info(normally primitive type) like game high score in any game.
In the Android documentation says how to relate SharedPreferences to XML but there's no need to use SharedPreferences if you don't want the data to be stored forever, you can store the game's state using the Activitys lifecycle methods with no problem, but for example, if the user turns off it's phone or presses the back button to finish your Activity, then the savedInstanceState won't work and you will lose your data.
It's your call, if you want the game to be saved even if the user turns off his phone (I think this would be kinda radical, but if it's your requirement go ahead) then use SharedPreferences or a DB if it's complex data. If you want the game to be saved only when the user navigates in and out to your app, then it's safe to use the savedInstanceState.
Is there any disadvantage in transferring values from Activity A to Activity B with static fields of a third class instead of the ExtraBundle?
In my application, sometimes I have like 15 - 20 values that I need to transfer between two Activitys. In my oppinion, it is more lucid solving this with static fields from a sort of TransferHandler.
At the moment, I have one disadvantage in mind: When a value is not put into the Extras before starting Activity B, I will get an Exception. Solving it with static fields, it it possible that I forget to assign a value, and if that value was assigned before from somewhere else, it might be that a wrong value is used in Activity B. Nonetheless, I think this is a "programmer problem" and not a "program problem". So are there any further minusses or am I free to choice a way? How's with the performance of the two variants?
First of all, if you plan to use static values, you should use your Application class to do this (because Android system assures you that it is a true singleton)
Thus, you can store your datas in attributes of your custom Application class, and use specific methods to store and get these values.
This will ensure you can't "forget" any values.
Also, with 15-20, I will strongly advice you to make a specialized POJO class to store all this...
I think the biggest disadvantage with using static classes for passing information in android is that static fields and objects can be cleared by the system at any time. That means that any static non final value can ALWAYS be null.
So it will probably work fine most of the time, but if you don't make sure to handle these null situations and your users start using your app they'll get a null pointer exception crash once in a while because the system decided it needed that memory stored in those static fields.
The best way for passing data between activities is by my opinion by using Intents, see here for a good example. Alternatively use a database or the the sharedpreferences.
Google also have a good read about pass data between Activities/Services here.
You cannot use a third class to transferring values form one activity to other. Here is the problem with it. You create one object in the activity-a then you store some values into it. Then after for using the values you need to create one more object in the activity-b then the object created in activity b will not be having the values you assigned in activity-a.
You can use SharedPreferences class to store valuo of variables:
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = settings.edit();
// With editor you put data
editor.putString(firstName, "John");
editor.putString(lastName, "Smith");
editor.commit();
You can access this data in all activities:
// With settings you access to data in different activities
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
String firstName = settings.getString(firstName, null);
String lastName = settings.getString(lastName, null);
I am new to Android app development and would like a little information on global variables. I have done a lot of searching and I understand that in the class files you can declare a global variable(correct me if I'm wrong). I have taken a look at a lot of posts including Android - Global variables? . They have not helped me to understand what I would like to know. My goal is to be able to create variables that will change and remain changed after the app has been terminated. The idea that I have is that I would like to have a main page that then branches to a bunch of other pages and have a global variable that saves what page your are currently visiting so that when you resume you can press a button labeled continue and it will bring you back to the page that you were previously on. If there is a better way than global variables, I am open to alternatives, thanks in advance!
You can use SharedPreferences to do that. In your activity, use:
SharedPreferences preferences = this.getSharedPreferences("name", Context.MODE_PRIVATE);
preferences.edit().putString("lastPage","mainPage").commit;
To read your saved data, use:
String lastPage = preferences.getString("lastPage");
Read http://developer.android.com/reference/android/content/SharedPreferences.Editor.html to know the types that you can store.
You can't have variables - global or otherwise - persist after the app has been terminated unless you write them to a permanent storage. In Android this can be done with an ObjectOutputStream to write an object to the filesystem or SharedPreferences, which save key/value pairs for retrieval. You will have to save and set your variables when you need them.
But you shouldn't do global variables anyway.
I am looking for a way to create dynamic preferences where I don't need to hard code the preference key and I could have a variable number of preferences.
Basically, my application will let the user create a multiple number of profiles and each of these profiles will save custom values for a fixed number of preferences.
So this way, the user does not have to change the preferences every time he wants this app to run differently, he can just switch the profile.
One way I think will work is by subclassing all the standard Preference classes and calling their setKey method with my custom preference key, containing the profile name, but this is ugly.
So is there a cleaner and more standards compliant way to do this?
Regards,
Dhruwat
You can save different preferences in a different file for each user using the getSharedPreferences method:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
That way, you can do something like this:
SharedPreferences settings = getSharedPreferences("prefs_user_"+user_id, 0);
// from now on you can use use the normal way to set or get the preferences
I'm assuming you are using an id in order to identify them users.