I use token based authentication in my app. When user logins through Android app the server returns token which needs to be sent with each subsequent request.
I need to store that value on the devices. Since token is a simple string, I thought I'd use SharedPreferences to hold that value.
Two think confuse me on which method save token in sharedpref. and other one is where to receive the token while implementing change password.
Use Aynch task For network task
Use Post Method Api
try something like this.. Create a class for saving values
public class SharedPreferenceCustom {
private String defValue = "";
private SharedPreferences sharedPreferences;
public SharedPreferenceCustom(Context context) {
sharedPreferences = context.getSharedPreferences("app_name", Context.MODE_PRIVATE);
}
public void setSharedPref(String inputKey, String inputValue) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
return sharedPreferences.getString(inputKey, defValue);
}
}
and call whenever needed
Call by
SharedPreferenceCustom sp = new SharedPreferenceCustom(mContext);
sp.setSharedPref("KEY", "VALUE");
// or
sp.getSharedPref("KEY");
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.
Hey guys I am unable to save a boolean value using SharedPreferences. The value is ALWAYS true for some reasons. Here is how I save the value:
public static void setSharedPreference(Context ctx, String keyValue, boolean value){
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(keyValue,value);
editor.commit();
}
And this is how I get it back:
public static boolean getBooleanPreference(Context ctx, String keyValue){
boolean prefValue;
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
prefValue = sp.getBoolean(keyValue, false);
return prefValue;
}
What is wrong?!
Your code is syntactically correct, but I suspect you are passing different Context while saving than you are passing while reading from prefs. This will result in accessing different shared preferences storage. This is especially easy to step on if you are doing your writes and reads in different activities and decide to pass this as context. Unless there's a reason for doing so then you most likely want to reach your preferences from anywhere in your app then use always application context instead (getApplicationContext()).
Everything is correct in your code.
The ONLY possibility of a mistake is when you are calling these methods. Please use getApplicationContext() while putting and retrieving data.
And please do a "Clear data" for the app and start with a clean SharedPreference.
I have a RESTful web-service, I am retrieving a data to android device
So here My ip address/Doamin name may change like..
192.168.0.1 or1-255 etc or It may be www.stackexchange.com or www.stackoverflow.com
Like my data will be stored in 192.168.0.1/rst/api/login or www.stackoverflow.com/rest/api/sitemview
So to over come this I want to use domain name as One time when i install application
in my application I have other pages like Login,display list-view, Single ItemView.
So this domain name should stored in device and pass to other activities every time when I use.
I used shared preferences like
public static void savePreferences(Context ctx, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
so when they load
public static Object loadSavedPreferences(Context ctx, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
return sharedPreferences.getString(key, "");
}
So here My problem is that This one time value is not permanent when ever I force close or Restart devise that passing value is not working
Any suggetion
If your domain name fixed, use below code.
public class WS{
public static final String domain="http://blah.ws";
}
Access it in each activity
with
String apiPath=WS.domain+your_rest_path;
I need to extract the application data using SharedPreferences in Xamarin.Android.
Here is what I have tried in android.
public static void SetAuthentication(bool authenticationValue)
{
var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
localSettings.Edit ().PutBoolean ("ValidUser", authenticationValue).Commit ();
}
public static bool GetAuthentication()
{
var retValue = false;
object value;
var localSettings = Application.Context.GetSharedPreferences ("Hello", FileCreationMode.Private);
localSettings.GetBoolean ("ValidUser", out value);
}
But somehow I feel this is not the right approach.
Any guidance is appreciated.
Thanks
On the Android platform, preferences are stored in a text file in the private folders of the Android application - there are 2 ways to access these SharedPreferences data files.
You can either use the "default" file for the application, or you can use a named file, using any name you want.
This second approach is what you have chosen to do by calling GetSharedPreferences with a filename.
I would suggest to just use the "default" preferences. This way has some advantages:
the code is simpler
the preferences can be accessed more easily in a PreferenceActivity later on
To do this, create your ISharedPreferences instance using:
ISharedPreferences localSettings =
PreferenceManager.GetDefaultSharedPreferences (mContext);
Once you have your "default" shared preferences in this manner, the rest of your code stays the same.
For more info, check out related questions:
How do I use SharedPreferences in Xamarin.Android?
save android app string value after close xamarin
I agree with Richard so just to be clear and complete I would do like this:
public static void SetAuthentication(Context ctx, bool authenticationValue)
{
ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
ISharedPreferencesEditor edit = pref.Edit();
edit.PutBoolean("ValidUser", authenticationValue);
return edit.Commit();
}
public static bool GetAuthentication(Context ctx)
{
ISharedPreferences pref = ctx.GetSharedPreferences("your_app_preferences", FileCreationMode.Private);
return pref.GetBoolean("ValidUser"), null);
}
I hope this will make you feel happier.