I made a simple counting app where there is Text-view that contains the counted number, and I want to save the counted number so that when I close the app the counted number should be there.
You should use SharedPreferences. Save the count to preference every time it is updated. Read and load the saved value in TextView when app starts next time.
The best solution for your problem is to use SharedPreference.
create another class called SaveCounterValue and copy the following code to that class
public class SaveCounterValue {
static final String PREF_COUNTER= "counter";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setCounter(Context ctx, int counter)
{
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(PREF_COUNTER, counter);
editor.commit();
}
public static Long getCounter(Context ctx)
{
return getSharedPreferences(ctx).getInt(PREF_COUNTER, 0);
}
}
Then in your activity after conter++ you copy the below code
SaveCounterValue.setConuter(context, counter);
Related
I'm thinking how best to save the age of a user from 2 Date of Birth variables: YEAR and DAY_OF_YEAR. As age is a dynamic variable, I want the age variable creation to only be called once as I don't want to have to call a function every time I want to refer to age in the same user session.
Then when the user closes the app and reopens, I want age to be initialised again incase their age has changed.
So how can I save age for the user session and then initialise it again once the app reopens?
Use "Static" Variable
private static int myValue;
public static int getMyValue() {
return myValue;
}
public static void setMyValue(int myValue) {
MyActivity.myValue = myValue;
}
Static Values will only be held only as long as the app is Open
anytime you need to set new value you call setMyValue()
First of all, calculate the age in the application class and store it in shared preference, and use it wherever you want from shared preferences.
Also check in application class if calculated age and age in shared preference is same or not, if it is same no need to update preference else update shared preferences.
Suppose the name of your age calculation method is calculateAge(),
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
int age = calculateAge();
if (a != getAge()) {
saveAge(this, a);
}
}
int calculateAge() {
return age;
}
public static void saveAge(Context context, String lang, int age) {
SharedPreferences sharedPref = context.getSharedPreferences(quesID, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("age", age);
editor.apply();
}
public static int getAge(Context context) {
SharedPreferences sharedPref =
context.getSharedPreferences(context.getString(R.string.filename),
Context.MODE_PRIVATE);
return sharedPref.getInt("age", 0);
}
}
and to use age anywhere in app use App.getAge();
SharedPreferences doesn't work correct in one existing apps. I tried many different ways but still not working. Always get default values app start again.
It's working when I use same code in created new app.
It's working all of other existing apps.
Do you know why?
String default_user = "Default_User";
SharedPreferences pref = this.getSharedPreferences("TEST_SHAREDPREF", MODE_PRIVATE);
String user = pref.getString("user", default_user);
Log.d("SHARED CHECK", user);
if (user.equals(default_user)) {
SharedPreferences.Editor edit = pref.edit();
edit.putString("user", "new_user");
boolean ok = edit.commit();
user = pref.getString("user", default_user);
Log.d("SHARED WRITE", user);
Toast.makeText(this, user + " Save process: " + ok, Toast.LENGTH_LONG).show();
} else {
Log.d("SHARED READ", user);
Toast.makeText(this, "READ SharedPrefs: " + user, Toast.LENGTH_LONG).show();
}
EDIT: log results
that block always return this for which is incorrect app and I don't know why
//first run
SHARED CHECK Default_User
SHARED WRITE new_user
//each time after first
SHARED CHECK Default_User
SHARED WRITE new_user
That block always return this for which are all apps
//first run
SHARED CHECK Default_User
SHARED WRITE new_user
//each time after first
SHARED CHECK new_user
SHARED READ new_user
When you call apply() or commit() the changes are first saved to the app's memory cache and then Android attempts to write those changes onto the disk. What is happening here is that your commit() call is failing on the disk but the changes are still made to the app's memory cache, as is visible in the source.
It is not enough to read the value from the SharedPreferences as that value might not reflect the true value that is on the disk but only that stored in the memory cache.
What you are failing to do is to check the boolean value returned from the commit() call, it is probably false for your problematic case. You could retry the commit() call a couple of times if false is returned.
Just use below method and check.
Create one Java class AppTypeDetails.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class AppTypeDetails {
private SharedPreferences sh;
private AppTypeDetails() {
}
private AppTypeDetails(Context mContext) {
sh = PreferenceManager.getDefaultSharedPreferences(mContext);
}
private static AppTypeDetails instance = null;
public synchronized static AppTypeDetails getInstance(Context mContext) {
if (instance == null) {
instance = new AppTypeDetails(mContext);
}
return instance;
}
// get user status
public String getUser() {
return sh.getString("user", "");
}
public void setUser(String user) {
sh.edit().putString("user", user).commit();
}
// Clear All Data
public void clear() {
sh.edit().clear().commit();
}
}
Now Set value to SharedPreferences.
AppTypeDetails.getInstance(MainActivity.this).setUser(<user name>);
Get Value form SharedPreferences.
String userName = AppTypeDetails.getInstance(MainActivity.this).getUser();
Now do any thing with the userName.
Always check
if(userName.trim().isEmpty())
{
// Do anything here.
}
because In SharedPreferences we set user name blank ("")
or
you can set user name null in SharedPreferences then you need check
if(userName != null){
//do anything here
}
For clear data from SharedPreferences.
AppTypeDetails.getInstance(MainActivity.this).setUser("");
or
AppTypeDetails.getInstance(MainActivity.this).clear();
One thing you could try is to get a new SharedPreference instance after committing and see what happens:
SharedPreferences pref = this.getSharedPreferences("test", MODE_PRIVATE);
String user = pref.getString("user", default_user);
if (user.equals(default_user)) {
pref.edit().putString("user", "new_user").commit();
SharedPreferences newPref = this.getSharedPreferences("test", MODE_PRIVATE);
user = newPref.getString("user", default_user);
}
Your editor is committing a new preference map into disk, but it is possible that the old SharedPreference instance is not notified of the change.
Instead of using edit.commit();, you should use edit.apply();. Apply
will update the preference object instantly and will save the new
values asynchronously, so allowing you to read the latest values.
Source - Also read detailed difference between commit() and apply() in this SO Post.
The "Source" post referenced above also states pretty much the same problem and switching to apply() seems to have resolved the issue there.
Problem statement in the referenced post:
The problem is that when I am accessing this values, it is not
returning updated values, it gives me a value of SharedPreferences.
But when I am confirming the data in XML file ,the data updated in
that.
PS: And the reason that the same code block is not working on this one app and working on all other apps could also be that you are either using the block at different places or updating the value somewhere else too.
Your code is right, the code works on any app very well, looks like that in some part of your app the shared preferences are been modified, the only way to find a solution is review all your code, because if this problem only happens on one app, it's somewhere on your app that the shared preferences are been modified, for good practices, you should have only one file class for the management of your preferences on that way you can comment or find usage for a method and you can find where the shared preferences was been modified.
BTW the best way to store an user, password, or any account info is using Account Manager.
For good practices you can see this sample PreferenceHelper class.
public class PreferencesHelper {
public static final String DEFAULT_STRING_VALUE = "default_value";
/**
* Returns Editor to modify values of SharedPreferences
* #param context Application context
* #return editor instance
*/
private static Editor getEditor(Context context){
return getPreferences(context).edit();
}
/**
* Returns SharedPreferences object
* #param context Application context
* #return shared preferences instance
*/
private static SharedPreferences getPreferences(Context context){
String name = "YourAppPreferences";
return context.getSharedPreferences(name,
Context.MODE_PRIVATE);
}
/**
* Save a string on SharedPreferences
* #param tag tag
* #param value value
* #param context Application context
*/
public static void putString(String tag, String value, Context context) {
Editor editor = getEditor(context);
editor.putString(tag, value);
editor.commit();
}
/**
* Get a string value from SharedPreferences
* #param tag tag
* #param context Application context
* #return String value
*/
public static String getString(String tag, Context context) {
SharedPreferences sharedPreferences = getPreferences(context);
return sharedPreferences.getString(tag, DEFAULT_STRING_VALUE);
}}
I used the below code pattern in one of my app and I always get the latest value stored in SharedPreferences. Below is the edited version for your problem:
public class AppPreference
implements
OnSharedPreferenceChangeListener {
private static final String USER = "User";
private static final String DEFAULT_USER = "Default_User";
private Context mContext;
private String mDefaultUser;
private SharedPreferences mPref;
private static AppPreference mInstance;
/**
* hide it.
*/
private AppPreference(Context context) {
mContext = context;
mPref = PreferenceManager.getDefaultSharedPreferences(context);
mPref.registerOnSharedPreferenceChangeListener(this);
reloadPreferences();
}
/**
* #param context
* #return single instance of shared preferences.
*/
public static AppPreference getInstance(Context context) {
return mInstance == null ?
(mInstance = new AppPreference(context)) :
mInstance;
}
/**
* #return value of default user
*/
public String getDefaultUser() {
return mDefaultUser;
}
/**
* Set value for default user
*/
public void setDefaultUser(String user) {
mDefaultUser = user;
mPref.edit().putString(USER, mDefaultUser).apply();
}
/**
* Reloads all values if preference values are changed.
*/
private void reloadPreferences() {
mDefaultUser = mPref.getString(USER, DEFAULT_USER);
// reload all your preferences value here
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
reloadPreferences();
}
}
You can set the value as below in your activity:
AppPreference.getInstance(this).setDefaultUser("user_value");
To get the updated value for saved user, use below code:
String user = AppPreference.getInstance(this).getDefaultUser();
Hope this solution will fix the problem you are facing.
For saving and retrieving data from SharedPrefrence create a util type methods in your Utility class:
Below I have given code snippet for both the methods i.e for saving and retrieving SharedPrefrence data:
public class Utility {
public static void putStringValueInSharedPreference(Context context, String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringSharedPreference(Context context, String param) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(param, "");
}
}
Now you just need to call Utility.putStringValueInSharedPreference(Activity_Context,KEY,VALUE); to put data in prefrence and Utility.getStringSharedPreference(Activity_Context,KEY); to get value from prefrence.
This methodology reduces chances of error; May this will be helpful for you.
I recommend controlling your preference check with another preference value.
String user = pref.getString("user", default_user);
In your preference check:
String getStatus = pref.getString("register", "nil");
if (getStatus.equals("true")) {
// move on code stuff
}
else{
// ask for preferences
}
In the part where the preference is added.
edit.putString("user", "new_user");
editor.putString("register", "true");
edit.commit;
Don't know if this is correct or not, but you can implement a Shared preference change listener and you can log in that and check if the shared preference is not called again in any other class, which is again setting the value to Default user.
I Mean you got to make sure that there is no other code resetting the value of user.
The code itself looks fine and you say it works in other apps. Since you have confirmed the XML file gets properly created, the only remaining option is that something happens to the file before you read it during app launch. If there is no other code in the app that handles any shared preferences, then something must wipe the file during the launch.
You should take careful look at launch configuration of this particular app and compare to other apps where this is working. Maybe there is some option that wipes user data when app is started. I know there is such an option at least for emulator (in Eclipse), but I am not sure if you are running this in emulator or device.
You should also try launching the app directly from the device instead of IDE. This tells if the problem is in the app itself or IDE configuration. And try moving this from onCreate (where I presume this is) to onResume and compare does it work when you resume to the app versus when you completely restart it.
Finally I solved that problem.
A method was added by one of other developers.
All files under data/data/packageName folder except libs folder were being deleted by this method.
I think they tried delete cache folder.
Removed this method and it solved.
This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 7 years ago.
So I'm just trying to save a string.. But everytime I rerun the app, I get null for the saved String :/ I'm 100% sure I'm calling the save method, and that the string it not null when I'm saving it.
public class CFUser {
private final static String ID_KEY="myUserID";
private static String userID;
public static String getUserID(Context context) {
if(userID==null) {
SharedPreferences prefs= context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
userID=prefs.getString(ID_KEY, null);
}
return userID;
}
public static void setUserID(String id, Context context) {
userID=id;
Log.d("saving", id);
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
prefs.edit().putString(ID_KEY, userID);
prefs.edit().apply();
}
public static boolean isLoggedIn(Context context) {
return getUserID(context)!=null;
}
}
many thanks!
In this code, you are creating two different SharedPreferences.Editor Objects:
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
prefs.edit().putString(ID_KEY, userID);
prefs.edit().apply();
So that means you are putting the String in Editor1, but are committing the (non-existant) changes of Editor2.
You need to do it this way:
SharedPreferences prefs=context.getApplicationContext().getSharedPreferences(ID_KEY, 0);
SharedPreferenced.Editor edit = prefs.edit();
edit.putString(ID_KEY, userID);
edit.apply();
At the moment the name of your entire SharedPreferences file is myUserID because of how you're retrieving the SharedPreferences. Instead use the following. This isn't causing the issue but I'm assuming you don't want the SharedPreferences file as your ID key...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Then when you're writing to the preferences make sure you're using the same Editor.
Editor editor = preferences.edit();
editor.putString(ID_KEY,userID);
editor.apply();
I am working on an Android project where a user can store some data but is able to delete and change/alter/update the values, I have been searching for a while now for a tutorial, but are not able to find any, so I was wondering, Is it possible to use SharedPreferences for that?
While you can always read the docs and know more about SharedPreferences, for a quick start here are few static methods from one of my project which you can use.
public static boolean getBooleanPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(key, false);
}
public static void setBooleanPrefs(Context ctx, String key, Boolean value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putBoolean(key, value).commit();
}
public static String getStringPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getString(key, "");
}
public static void setStringPrefs(Context ctx, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putString(key, value).commit();
}
public static int getIntPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getInt(key, 0);
}
public static void setIntPrefs(Context ctx, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putInt(key, value).commit();
}
public static void clearPrefs(Context ctx) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().clear().commit();
}
So far if data is limited to some values, yes you can use SharedPreferences for that. You can easily update/alter/clear values in SharedPreferences.For usage of Shared preferences, refer these
Android Shared preferences example
http://developer.android.com/guide/topics/data/data-storage.html#pref
http://www.tutorialspoint.com/android/android_shared_preferences.htm
But if your data is not limited and have some repititive type of values to be stored.For eg. data of app users, their info and all that, then you should go for local database using SQLite. For SQLite,you should go through this tutorial
For pros and cons of SQLite and SharedPreferences, you should go through this answer
shared preference is good way to store values.
need to declare shared preference and stored value to it like.
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
Editor editor = prefrs.edit();
editor.putString("key",abc);
editor.commit();
you can easily get that value like below...
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String name = prefs.getString("key", "default");
you can delete that stored value and can use for stored new value like below
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editor = prefrs.edit();
editor.clear();
editor.commit();
finish();
A set of questions about SharedPreferences that I was looking for:
What, Why, When?
How does it work inside?
The Best Practice to use it?
Only some of those question were answered here. That's why I made some investigations, and tests.
As I've answered on my own question I've decided to share answer with other people.
I've wrote a little article that can also be found here.
Best Practice: SharedPreferences
Android provides many ways of storing application data. One of those ways leads us to the SharedPreferences object which is used to store private primitive data in key-value pairs.
All logic are based only on three simple classes:
SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener
SharedPreferences
SharedPreferences is main of them. It's responsible for getting (parsing) stored data, provides interface for getting Editor object and interfaces for adding and removing OnSharedPreferenceChangeListener
To create SharedPreferences you will need Context object (can be an application Context)
getSharedPreferences method parses Preference file and creates Map object for it
You can create it in few modes provided by Context, it's strongly recommended to use MODE_PRIVATE because creating world-readable/writable files is very dangerous, and likely to cause security holes in applications
// parse Preference file
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
Editor
SharedPreferences.Editor is an Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
Use simple interface to put values in Editor
Save values synchronous with commit() or asynchronous with apply which is faster. In fact of using different threads using commit() is safer. Thats why I prefer to use commit().
Remove single value with remove() or clear all values with clear()
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
// put values in editor
editor.putBoolean("key", value);
editor.put..("key", value);
// remove single value by key
editor.remove("key");
// remove all values
editor.clear();
// commit your putted values to the SharedPreferences object synchronously
// returns true if success
boolean result = editor.commit();
// do the same as commit() but asynchronously (faster but not safely)
// returns nothing
editor.apply();
Performance & Tips
SharedPreferences is a Singleton object so you can easily get as many references as you want, it opens file only when you call getSharedPreferences first time, or create only one reference for it.
// There are 1000 String values in preferences
SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 4 milliseconds
SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
As SharedPreferences is a Singleton object you can change any of It's instances and not be scared that their data will be different
first.edit().putInt("key",15).commit();
int firstValue = first.getInt("key",0)); // firstValue is 15
int secondValue = second.getInt("key",0)); // secondValue is also 15
When you call get method first time it parses value by key and adds this value to the map. So for second call it just gets it from map, without parsing.
first.getString("key", null)
// call time = 147 milliseconds
first.getString("key", null)
// call time = 0 milliseconds
second.getString("key", null)
// call time = 0 milliseconds
third.getString("key", null)
// call time = 0 milliseconds
Remember the larger the Preference object is the longer get, commit, apply, remove and clear operations will be. So it's highly recommended to separate your data in different small objects.
Your Preferences will not be removed after Application update. So there are cases when you need to create some migration scheme. For example you have Application that parse local JSON in start of application, to do this only after first start you decided to save boolean flag wasLocalDataLoaded. After some time you updated that JSON and released new application version. Users will update their applications but they will not load new JSON because they already done it in first application version.
public class MigrationManager {
private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
private final static int PREFERENCES_VERSION = 2;
public static void migrate(Context context) {
SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
checkPreferences(preferences);
}
private static void checkPreferences(SharedPreferences thePreferences) {
final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
if (oldVersion < PREFERENCES_VERSION) {
final SharedPreferences.Editor edit = thePreferences.edit();
edit.clear();
edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
edit.commit();
}
}
}
SharedPreferences are stored in an xml file in the app data folder
// yours preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
// default preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
Android guide.
Sample Code
public class PreferencesManager {
private static final String PREF_NAME = "com.example.app.PREF_NAME";
private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
private static PreferencesManager sInstance;
private final SharedPreferences mPref;
private PreferencesManager(Context context) {
mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static synchronized void initializeInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesManager(context);
}
}
public static synchronized PreferencesManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return sInstance;
}
public void setValue(long value) {
mPref.edit()
.putLong(KEY_VALUE, value)
.commit();
}
public long getValue() {
return mPref.getLong(KEY_VALUE, 0);
}
public void remove(String key) {
mPref.edit()
.remove(key)
.commit();
}
public boolean clear() {
return mPref.edit()
.clear()
.commit();
}
}
Yakiv has mentioned everything about preferences so neatly and nicely. I just want to add one more point. While editing data in shared preferences we usually do
mPref.edit()
which creates a new object of SharedPreferences.Editor type every time which can result in unnecessary objects in memory. So you can maintain a reference to editor object too and save memory and object creation time and corresponding garbage collection time.