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.
Related
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.
I want to make an Android application which shows questions on the go on the basis of user selection. But I won't use a server, and so the questions have to be bundled with the app. But adding the whole questions would not be a great design, so either SQLite database can be used, or xml metadata can be used. But SQlite bundling I heard makes the app large in size. Is that so? And could someone explain how to refer to a xml file with self-defined metadata, to create questions on the fly. What will be the best way to do this?
the SQLite DB is on the phone already, I've used it a few times with no big jump in .apk size.
If you are looking for an easy-to-use stored hashmap, try SharedPreferences! Though I wouldn't use it for a heavy solution, the implementation guarantees ACID and is very straightforward. you can make several different hashmaps and name them different things with SharedPreferences http://developer.android.com/reference/android/content/SharedPreferences.html
I declare:
private SharedPreferences anchorHash;
in onCreate:
anchorHash = getSharedPreferences(getString(R.string.anchor_hash), MODE_PRIVATE);
inonPause:
SharedPreferences.Editor editor = anchorHash.edit();
editor.clear();
for( String s: anchors.keySet()){
//it's a another hashMap I want to write here, but you can do this however you like
editor.putString(s, anchors.get(s));
}
editor.apply();
//or commit() if you need to know about the success ( it'll happen )
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.
I have created a service that writes some information about a widget once a user places it on home screen(the info is picked up from the confutation activity)..i also write down the number of widgets the user has set up.
Once the user removes the widget i delete that info in the shared preferences.
What i have experienced is that if user places for example 2 widgets, then removes one, then places one again, doing all those actions fast, the shared preferences file gets inconsistent values in it. Sometimes it works ok but most of the time i get stuck with wrong values in it.
I am using apply(), i've tried with commit but same thing happens.
The values i store in the shared preferences are crucial for the system to work, without it the widgets are useless since they are backed up by info from internet based on the user configuration which is written in preferences.
Is switching to a database solution more reliable or any other viable solution which will fix this "race condition"? (maybe forcing my own mechanism of synchronization, but as far as i've understood from docs, apply() is already synchronized, and the read/write should first go to RAM which should make it fast and i shouldnt be experiencing any problems like this since the user cant physically manage to delete a widget and place a new one faster then 2-3 seconds top!)
Try using the synchronized keyword in working with the SharedPreferences itself. For example, here is a method that could be used when setting an application String in the SharedPreferences of an Android app:
public synchronized static void setAppString(Context context, String pref,
String val) {
SharedPreferences sp = context.getSharedPreferences(
APP_PREFS_UNIQUE_ID, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(pref, val);
editor.commit();
}
For few/simple key-value pairs, you might not need the overhead of a database paradigm.
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.