Saving and restoring sets of preferences - java

Are there any nice ways to save and then restore the values for a group of preferences (i.e. stored using SharedPreferences) in Android?
For my game app, I have about 10 preferences concerning how the game should be rendered. What I'd like to do is add various profiles that can be selected, where each profile would set the values of the 10 preferences. For example, I might have a "low battery usage" profile that would set all the rendering preferences to values that use the least amount of battery or a "high detail" profile to set all the rendering preferences to their highest settings.
I will also have several preference that are not set by these profiles. For example, I will have a preference that stores the name of the current active profile.
What options do I have about how I save/restore profiles? How would changing profiles be implemented?

IMHO basically there are three ways, how to achieve your goals:
Create set of SharedPreferences - separate for each profile, like:
settingsCommon=context.getSharedPreferences("MyCommon", MODE_PRIVATE);
settingsLowBattery=context.getSharedPreferences("MyLowBattery", MODE_PRIVATE);
Add to each preference key smth like
suffix which will point to profile:
int getIntPreference(SharedPreferences settings, String profile, String key, int defValue)
{
String fullKey=key+"."+profile;
return settings.getInt(fullkey, defValue);
}
Extend SharedPreferences class and
implement your own, including
creating/parsing of any kind XML

Related

How to save a state in Shared preferences on Android Java?

In my application after login I have to save state in shared preference to change the app view on a button click. can anyone help me to save state in shared Preferences and on a button click i need to replace the initial state with the new one.
You can't save a layout. You can save a layout id- but I wouldn't suggest it. Resource ids are not stable across builds, so any update would break it. Your best bet is to create an enum with whatever values you wish it to have, save the enum, and later on convert the string back into an enum when you read it in. Then hold a map<enum, resourceId> in code that maps to the correct resource id.

How to persiste or save the JavaFX UI state?

This has been asked here:
How to persist JavaFX GUI State?
And has the tag javafx-2. But no answers.
Gonna ask again and put in more tags.
I'm looking for something like what was done in JSR 296: Swing Application Framework where the demo application remembers it's window size, location etc. E.g if the user maximized the window, and then closes, opens the program again, the window is maximized.
You can store basic information using the Preferences API.
Depending on the operating system, the preferences are saved in different places (for example in Windows, they are stored in the registry file).
Typical use goes like this:
To store a value:
Preferences prefs = Preferences.userNodeForPackage(MyClass.class);
prefs.putBoolean("isWindowMaximized", true);
To get a value:
Preferences prefs = Preferences.userNodeForPackage(MyClass.class);
boolean value = prefs.getBoolean("isWindowMaximized", false);
You will find more information about this API in this Oracle tutorial.

Storing data in Android

I am currently working on my first app and I have decided to do it on android. I have the main activity layout the way I wish and the Time/Date displaying dynamically.
What I am needing help with is I need the app to save the date and time whenever a button is pressed. This data will need to be available for 1 week (7 Days) and then it may be overwritten the following week to save space on the device.
Ideally there would be two button presses a day, one to clock in/clock out (App to keep track of my hours at work and calculate pay). What is the best way to go about this? Can you guys point me in the right direction to storing this data?
I thought about using Parse but then an online connection would be needed, correct? Is there anyway to do this locally and then maybe I can implement online storage later?
If the data you want to save isn't very complex I'd use SharedPreferences.
Here's an example:
To write data:
SharedPreferences sharedPref = getSharedPreferences("com.example.myapp.PREFERENCE_FILE_KEY",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong("clockIn", clockIn.getTime());
editor.commit();
To read data:
SharedPreferences sharedPref = getSharedPreferences("com.example.myapp.PREFERENCE_FILE_KEY",
Context.MODE_PRIVATE);
Date clockIn = new Date(getResources().getLong("clockIn"));
Take a look at this for more info: https://developer.android.com/training/basics/data-storage/shared-preferences.html
The simplest way would be to use SharedPreferences, but a more comprehensive, dynamic storage would be using Sqlite.
Shared Preferences
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
prefs.putLong(FIRST_TIME,nix timestamp).commit();
prefs.putLong(SECOND_TIME, nix timestamp).commit();
And retrieve the same way:
long firstTime = prefs.getLong(FIRST_TIME);
long secondTime = prefs.getLong(SECOND_TIME);
Best way is to store in local db(Sqlite).

Shared preferences "bypass default value"?

So I have a few different checkboxes in my app and I'm changing their texts with the click of a button. What I'm trying to do is to save those strings in Shared Preferences but I have one problem. When creating shared preferences I have to enter a default value, but I already did set a default value in XML file, and I have too many checkboxes to set a default value for every single one of them. So my question is: is there a way to "bypass" this default value? This is my code so far:
private String getItemQuantity(String key){
SharedPreferences itemQuantitySP = getApplicationContext().getSharedPreferences("bifrostPrefs", android.content.Context.MODE_PRIVATE);
return itemQuantitySP.getItemQuantitySP(key, );
}
Thank you!
You can put your default values into constants to ie. const.java file, then instead of putting default values in XML files set initial value in Activity onCreate using shared preference value. Of course read your shared preference value using default values from const.java.

How do I persist searched text in the SearchViews text field on search?

I have a SearchView in my action bar. When the user searches for a query and presses the "Go" button on keyboard, the search intent gets passed to my activity but the search field collapses and the query text is lost. How can I prevent this from happening? I would like the text to remain in the search field until explicitly cleared by the user.
Thanks
You can store the search request either in a String variable or in the shared Preferences when the "Go" button is clicked by using getQuery() when the search event happends (setOnSearchClickListener) and then write them back in either as the Query (setQuery) or as a hint (setQueryHint).
Edit (Based on the Question you can read below this answer)
How can you store the query string if the activity is recreated after every search? If you have some service that is persitent in the runtime of your aplication you could store it there, but that isn't that elegant. The easyest way to do it is to use the SharedPreferences. This is a persitant (key,value)-storage that you can use throughout your app to store and retreive values.
You initiate a SharedPreference with
SharedPreferences prefs = getSharedPreferences("mysharedprefenrences", 0);
The String can be anything you want. Whenever you use the same String to create a SharedPreferences-Object in your app, you will have acces to these values again.
To get a String, like your search query, use
String aString = prefs.getString("searchQuery", "")
with the second String being the default, if the query isn't set yet (in this case "").
When the setOnSearchClickListener is enacted you can store the Query by using an Editor.
Editor editor = prefs.edit();
editor.putString("searchQuery", queryString);
editor.commit();
Now the next time the activity is created, instead of the default String your stored String will be found.
My solution turned out to be dead simple. Apparently, I wasn't setting the android:launchMode properly for the Activity. Ideally an activity that provides search functionality should be a single top so the user doesn't have to navigate backwards through all the previous searches upon clicking the "Back" button. Mine wasn't. Therefore, every time I searched, a new instance of my search activity was initiated and added to the view stack.
I added this to my manifest file under the correct activity.
android:launchMode="singleTop"

Categories

Resources