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.
Related
I am designing a simple application that will count how many times a user has tapped on a imageView. My question is what would be the best way of saving and reading this file. Any suggestions? I am thinking something like using Parse.com's local database. I have tried it, but I could not get it working the way I wanted. I am still a beginner, so please not so fancy suggestions.
Try to save data in SharedPreference. SharedPreference works like database for application on device that will be stored until any one has unistall app from device.
To create sharedPrefernce-
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To store data -
prefs.edit().putInt("key", int_value).apply();
To retrieve data-
// use a default value
int l = prefs.getLong("key", default_value);
Simplest options is always thebest option, go with shared preferences
Here is simple tutorial from google http://developer.android.com/training/basics/data-storage/shared-preferences.html
It will store your data in application local file. Take a note of that there are different shared preferences in example getPreferences() will return file specific for activity you used this method. While getSharedPreferences() will return application global file.
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 would like to be able to save my users session or sharedPrefrences in a way that if the user kills the application and you start it it would look like this.
Button one = Start Activity with Blank Preferences
Button Two = List of Saved Sessions of Preferences and once clicked all put into the Starting activity.
Is this possible and if so how would I go about doing that?
Thank you!
Yes you can do that and it is good to use sharedPreferences if you just have to store some session variables. But if it is more, then go for database.
Do clear sharedPrefences in your application you need to do this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(activity);
Editor editor = settings.edit();
editor.clear();
editor.commit();
For reading the preferences, you can keep a sharedPreference with the count for the seesions. While saveing the prefences, always save with the strings session1, session2, session3 etc. So, while accessing them based on count, prepare a loop and form the string and access all the session variables and show them.
The reason why I didnt suggest you to do getAll() for sharedPreference is that, you may save few other things in sharedPreference. So by forming strings yourself, while reading you can just get the sessions and not other data saved in sharedPreference.
I hope you understand what I meant
Is this possible
I would say yes, depending on exactly what you mean.
if so how would I go about doing that?
SharedPreferences has a couple different functions to do something like this, depending on exactly what you want. You can get a Map of all preferences that are stored after clicking Button2 with getAll() or a set of preferences with a certain String such as "userName" or something similar with getStringSet(). Play around with the functions it offers and see if it gives you what you are looking for.
Also take not of the warnings of these functions
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
When I originally wrote and published my app, I was using a custom written activity to handle application settings. I used custom file name to store shared preferfences, like this:
getSharedPreferences("custom_settings_file",MODE_PRIVATE);
But now I'm refactoring my app and I would like to implement PreferenceActivity or PreferenceFragment and an xml file with PreferenceScreen section. Every tutorial or example that I've seen is using
getDefaultSharedPreferences(context);
to retrieve shared preferences, because PreferenceActivity assumes default filename to store preferences and there's no way to tell it to use a different one(at least I couldn't find one after an hour of searching and reading documentation).
So now I have a problem. If I just simply use the new default file, existing users of my app will lose their settings when they update the app, because the new application will not know anything about "custom_settings_file". What would be the best way to move the data from an old file to a new one on app update?
Here are the possible options that I could come up with:
Extend Application class and implement a piece of code in onCreate() so that every time my app is launched, it would check for existence of "custom_settings_file" and move it's contents to the new one. But running a block of code on every app launch seems like wasting too much processing resources for an operation that only needs to run once.
Just notify the user that their old settings are gone. But obviously this is not acceptable.
Is there a better solution, than option 1? Perhaps someone has already faced a similar problem?
What is preventing you from doing number 1 only once?
Just add a "migration" boolean to the new sharedpreferences.
If you also load the xml preference file then you can try this:
PreferenceManager.setDefaultValues(context, YOUR_PREFERENCE_NAME, MODE_PRIVATE, R.xml.preference_file, false);
If not (you want to add each preference item dynamically in your code) then you can do like this:
PreferenceManager pm = getPreferenceManager();
pm.setSharedPreferencesMode(MODE_PRIVATE);
pm.setSharedPreferencesName(YOUR_PREFERENCE_NAME);
In case you still want to use the defaultSharedPreference and process the migration then ... I'm writing this and I see Nicklas's answer, so I'm done here.
Could you add value in your new SharedPreferences that records whether you are a new install or an upgrade. If you don't have the setting in your sharedpreferences, check to see if you have an old preferences file in the way you were before. Then convert those preferences to your new method, and set your private setting indicating that it's been upgraded. Then just set the new value indicating the new state and you won't need to check your old preferences any more.
My application is used on multiple platforms so it saves it preferences to a file (rather than to the standard Android SharedPreferences).
Is there any easy of reusing the PreferenceActivity to save preferences to a file or is it a case of creating a whole new activity to do the job? If the latter is the case is there a layout I can use that will make the activity look like the normal preferences screen? PreferenceActivity uses com.android.internal.R.layout.preference_list_content but this doesn't appear to be available to apps for reuse.
Is there any easy of reusing the
PreferenceActivity to save preferences
to a file or is it a case of creating
a whole new activity to do the job?
Not really. I mean, you could subclass SharedPreferences, rip the guts out, and map it to your own data model, but that would be far, far worse for maintainability than just using SharedPreferences in the first place.
If the latter is the case is there a
layout I can use that will make the
activity look like the normal
preferences screen?
It's just a ListView. It will take you a lot more time to do this than to just use SharedPreferences.
PreferenceActivity uses
com.android.internal.R.layout.preference_list_content
but this doesn't appear to be
available to apps for reuse.
Sure it is. If you have the SDK installed, it's on your hard drive right now. Look in $ANDROID_HOME/platforms/$API/data/res/layout, where $ANDROID_HOME is where you have the SDK and $API is some API (e.g., android-2.1).
You can create a function that exports the data from SharedPreferences to a file.
Normally Preferences are saved into sharedpreferences when the user clicks on the prefrence item. Add your code to update your external dataholder on onPreferenceTreeClick() function.