This question already has answers here:
How can I save an activity state using the save instance state?
(35 answers)
How to save app settings?
(6 answers)
Closed 8 years ago.
I'm developing a level-based app, and I want to be able to save the user's level number (1, 2, 3 etc..) and then when the app starts get the level number and do something with it.
How can I do it?
Use Shared Preferences like so:
Create these methods for use, or just use the content inside of the methods whenever you want:
public int getLevel()
{
SharedPreferences sp = getSharedPreferences("prefName", 0);
int level = sp.getInt("levelReference", 1);
return level;
}
public void setLevel(String level)
{
SharedPreferences.Editor editor = getSharedPreferences("prefName", 0).edit();
editor.putInt("levelReference", level);
editor.commit();
}
The 1 in sp.getInt("levelReference", 1); means that the method will return 1 if the preference is not found, so the default level is 1.
You can call them like this:
int level = getLevel(); // level is now the level that the user is on
setLevel(4); // user is now on level 4
Use SharedPreferences for storing level number:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://android-er.blogspot.ru/2011/01/example-of-using-sharedpreferencesedito.html
If you read up in the documentation here you can see that to save data like a level number, you can use SharedPreferences. First, you'll need a SharedPreferences object, which you can obtain using
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Then to save a piece of data, use:
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("level", level);
editor.commit();
And finally, to get that level back later, use:
sharedPref.getInt("level", 0);
Good luck!
Related
I'm wanting to store a number of different user favorites (in this example a max of 5) in sharedpreferences.
The user will be able to add and delete these favorites from within the app.
I'm having trouble getting my head around how to achieve this (I assume some sort of looping is needed).
The gist of what I'm trying to do when a user adds a new favorite:
//init prefs
public static final String PREFS_NAME = "PREFS";
SharedPreferences sharedPreferences = null;
SharedPreferences.Editor sharedPreferencesEditor;
//onCreate
sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//method called when user adds new favorite
public void addFavorite(String fav) {
//int i = 0;
//int maxFavs = 5;
//check how many favorites are already stored in shared prefs, if any (is it under maxFavs?)
//if over maxFavs, display error
Toast.makeText(getApplicationContext(),"Favorite added",Toast.LENGTH_SHORT).show();
//else continue
//upon finding available favorite 'space' (less than permitted maxFavs), add to favorites in shared prefs
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString("fav_" + i, fav);
sharedPreferencesEditor.apply();
}
Am I getting the right idea here, or is there a better way to do what I'm intending to do? Hopefully it's clear from the above.
Store favorite count in preferences as an int and read & update it as needed. Also it would be better if you store favorites in preferences as (key : favoritedItemId, value boolean)
Even better: Use a proper local database for situations like this. Preferences is a primitive key value type storage intended for simplier cases like storing a users light mode preference.
Gave up and created a simple database following the example here:
https://inducesmile.com/android/android-sqlite-database-example-tutorial/
Still, if anyone has a solution I'd be interested to see!
I want to store a boolean variable and textview text on the device the app is running, so that even after clearing in recent apps i can use the recent booleab states to make changes remain the same. Or is there any way to get the last state even after clearing the app from the recent apps or onDestroy
You should check out Shared Preferences in Android.
Write to Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
#apelsoczi's answer is essentially correct, but here is a more detailed example which also includes boolean values, and String values, as asked in your question.
First get a reference to your apps Shared Preferences like this:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Then save your string and your boolean like this:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(YOUR BOOLEAN KEY, YOUR BOOLEAN);
editor.putString(YOUR STRING KEY, YOUR TEXT VIEW STRING);
editor.commit(); // if commit is not called then data not saved!
To retrieve the values do this:
boolean b = prefs.getBoolean(YOUR BOOLEAN KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);
String s = prefs.getString(YOUR STRING KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);
Shared Preferences is a way to store simple key value pairs of data - very useful for settings. For example say you have a value false for your boolean, and you want to save it, so what you do is you pass in a name for it (passing a name is important because you need that name to retrieve the value) and the actual value to save. When you want to retrieve it, you again pass in the name you had assigned it when saving it.
This question already has answers here:
Android global variable
(14 answers)
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
How to set values globally so that i can access from any activity or fragment.
For eg : activity_login.java > user_id need to store globally so every time any section which depends on user_id, checking and pulling data from backend will be easy instead of passing through activity (intent)
Edit :
i do need setter and getter from fragment or activtiy.
There are many ways to store values globally so it can be access from any where in application all classes :
Declare public static variable but it's not preferable for long storage.
Use shared preferences - SharedPreferences
Use database - SQlite
You can use any of one above alternative to access globally values.
Use Sharedpreferences.its safe, Here's the example https://www.tutorialspoint.com/android/android_shared_preferences.htm
Use sharedPreferences and access the values at any of your class
Put the below code at SamplePreferences.java
private static final String TOTALCOUNT = "total_count";
public static void setTotalCount(Context thisActivity, String id) {
Editor editor = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOTALCOUNT, id);
editor.commit();
}
public static String getTotalCount(Context thisActivity) {
SharedPreferences user_pref = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE);
return user_pref.getString(TOTALCOUNT, "0");
}
You can set the values from any of your class use below code
SamplePreferences.setTotalCount(thisContext, "2");
Access that value using below code
SamplePreferences.getTotalCount(thisContext);
I am running:
int value = mPreferences.getInt(key, 0);
mPreferences.edit().putInt(key, value+1).apply();
int newValue = return mPreferences.getInt(key, 0);
However I get the same result for value and newValue. The updated result only appears when I call getInt() later in the code. I thought updates to the SharedPreferences object using apply() would instantly be visible in the SharedPreferences object. Is this not the case?
If you want synchronous update you have to use
commit()
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#commit()
First of all commit() & apply() are the almost the same, major difference been that apply() is faster
I tried doing it the same way & it worked for me
Check this :
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
int a = sharedPreferences.getInt("a",0);
Toast.makeText(getActivity(), "a = " + a , Toast.LENGTH_SHORT).show();
sharedPreferences.edit().putInt("a", a+1).apply();
After checking the xml in data of the app, I got a as 1
I have a database which contains data. How is it possible to put the database in SD card only once? i mean -while it is being installed?
And also want some pictures to be pushed too.
Help me out please.
You can try SharedPreferences
private static final String FIRST_RUN = "first_run";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
//Assume true if the key does not yet exist
if (prefs.getBoolean(FIRST_RUN, true)) {
//Do your database operations
..............................................
} else {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(FIRST_RUN, false);
edit.commit();
}
just set one shared preference at first activity like splash of your app with Boolean value of false and do your work with database whatever u want in that condition after that set it with value true then it will not call that function until unless you re-install it or just not clear your data forcibly.