SharedPreferences returning null - android

I've created a class to save some username and password using the Android SharedPreferences, its seems that the methods for set both username and password are ok.
But everytime i try to get these, from within another activity or by just trying to print out the value i receiver nothing (if trying to print the value) or null (if trying to get on i activity).
Here is my code:
public class AuthPreferences {
private static final String KEY_USER = "userid";
private static final String KEY_PASSWORD = "mypassword";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context.getSharedPreferences("authoris", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
Log.v("MailApp", "User is " + user);
editor.apply();
if(editor.commit() == true) {
System.out.println("The user was set!");
}else{
System.out.println("The user was not set!");
}
}
public void setPassword(String pass) {
Editor editor = preferences.edit();
editor.putString(KEY_PASSWORD, pass);
Log.v("MailApp", "Password is " + pass);
editor.apply();
if(editor.commit() == true) {
System.out.println("The password was set!");
String mainUser = preferences.getString(KEY_PASSWORD, "456");
System.out.println(mainUser);
}else{
System.out.println("The password was not set!");
}
}
public String getUser() {
return preferences.getString(KEY_USER, "456");
}
public String getPassword() {
return preferences.getString(KEY_PASSWORD, "456");
}
Here is how i'm trying to get it:
preferences = new AuthPreferences(getActivity());
try {
String mainUser = preferences.getUser();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("App", "Could not get the user");
}

It is all because you use Activity as a context (you use result of getActivity() method as context). Since you got different activities you got different contexts so in result you are accessing different shared preferences files (XMLs). In other words you are writing to file A in activity A, and then read in activity B using file B as your source. This obviously is not going to work. To have this all work as you expect you shall always use the same context for data that you want to be accessed across many activities, in this case I recommend to use Application context. Technically, instead of calling getActivity() to get context in your fragment, you call getActivity().getApplicationContext() to get your application context, so you will be accessing the same shared preferences storage file, not matter what activity or fragment is doing that write or read.
Aside from this there's no need to call apply() and commit() as these two is kinda equivalent and do the same. Please check docs for more information.

Try replacing:
Editor editor = preferences.edit();
with
SharedPreferences.Editor editor = preferences.edit();
Then replace editor.apply(); with editor.commit();.

Instead of doing:
editor.apply();
do this:
editor.commit();
Also you need to commit your edits by using the methods somewhere:
AuthPreferences preferences = new AuthPreferences(getActivity());
preferences.setUser("USER_NAME");
preferences.setPassword("PASSWORD_VALUE");

Related

SharedPreference not available after app restart

I'm trying to figure out why I can't have access to my SharedPreference file after an app restart.
In my Application class in the onCreate I define my SharedPreference once :
pref = getSharedPreferences(Util.PREF_FILE_NAME, Context.MODE_PRIVATE);
editor = pref.edit();
And then in the onResume of my activity I call:
String userName = MyApp.getApplication().pref.getString(Util.USER_NAME, "");
But at this point the user name is always empty after a restart.
-To save my value :
MyApp.getApplication().editor.putString(Util.USER_NAME,"name").commit();
-For MyApp.getApplication() I've defined in my Application class:
public MyApp() {
instance = this;
}
public static MyApp getApplication() {
if (instance == null) {
instance = new MyApp();
}
return instance;
}
From my device I run a terminal app and with a 'cat' command I can see the content of my sharedPreference XML file. Even when I kill my app I can see the sharedPreference file is still there with my correct value inside.
But when I restart my app this value can't be read. What is happening there ?
I've noticed on a tablet with android Lollipop I've no problem but with a tablet with android Kitkat I have this problem.
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()
So Dont forget to your editor.commit()
Best Way which I using :
Util.class
public static void saveIntToUserDefaults(Context c, String Key, int value) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Key, value);
editor.commit();
Log.e("Saved:", "" + Key + "-" + value);
}
public static String getFromUserDefaults(Context c, String Key) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedpreferences.getString(Key, "");
}
public static void clearUserDefaults(Context c) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
}
I calling this wherever I need & its working superb

SharedPreferences Fragment not work

I try call SharedPreferences, and I pass a parameters but not work (not update and not put data)
I don't know I do wrong?
public void put(String value){
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
editor.putString("isFirstRunCheck", value);
editor.commit();
}
public void checkFirstRun3(){
SharedPreferences prefs = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
String name ="";
if (restoredText != null) {
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
}
if(name.equals("true")){
Toast.makeText(getActivity(), "click si ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "click no ", Toast.LENGTH_SHORT).show();
}
}
I put my "put()" I do not see it work
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
cbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cbx.isChecked()){
put("true");
}else{
put("false");
}
}
});
I'm not sure why you don't think this is working, but I'm guessing it is because your code doesn't do what you think it does.
First of all, the comment on this line is wrong:
name = prefs.getString("isFirstRunCheck", "");//"No name defined" is the default value.
The second parameter to getString() is the default value- in this case you are specify that the default value should be an empty string if you have not previously saved a value to the "isFirstRunCheck" key.
Second, you seem to be expecting a value of "si". However, you are only ever calling put("true") and put("false")- you never call put("si"), so your conditional in checkFirstRun3() will always be false.
As an aside, a String is an odd way to save boolean data. SharedPreferences has a getBoolean() and a putBoolean() that will likely suit your needs better.
Try to change
SharedPreferences.Editor editor = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE).edit();
to
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor spe = sp.edit();
Use
spe.putString("yourStringKey", yourStringValue).commit()
and then get your data using the "yourStringKey"
and don't forget to call your put(someData) method.

how to store a text in one activity and retrieve it in another activity.?

I have created an app for alarm service..such that a person can set a alarm to a specific time and the alarm will pop up as a notification..Now i want to create that alarm service app to a task reminder app such a way that at the time of creating or setting the task , user input the message in the edit text and save it and then when the alarm pops up , and if the user taps the notification , a new activity comes up and the message that he typed earlier is printed in front of him..(i mean the message is show as a text view to him) So Please tell me how could i do that using shared preferences..
In simple way just tell how could a load the stored string from the activity where the string was created and save with the help of a button and to load that same string and pass it in a text view to some other activity..
You can use shared-preferences to store data in one activity. and these data will be available in any activity with in same application.
http://developer.android.com/reference/android/content/SharedPreferences.html
example is available at http://developer.android.com/guide/topics/data/data-storage.html
Good Luck.......
I would like to suggest you to do all your preference tasks in your Application Utils.clas
// Declaration
public static String KEY = "SESSION";
// Method declaration :
public static void saveUserName(String userid, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", userid);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
// You can save the values in preference by calling the below :
Utils.saveUserName("12345",YourActivity.this);
// Finally you can retrieve the stored value by calling this code snippet :
String myUserName = Utils.getUserName(YourActivity.this);
Hope it helps
You can use SharedPreferences.
Using setSetting, you can set the text at caller class. Similarly, you can get the text which was set in the caller class using getSetting in the called class.
Method to set the Preference-
public void setSetting(String key, String value) {
if(getActivity() != null)
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
// Commit the edits!
editor.commit();
}
}
Method to get the preference-
public String getSetting(String key, String def) {
try
{
SharedPreferences settings = getActivity().getSharedPreferences("UserPref", 0);
return settings.getString(key, def);
}
catch(Exception e)
{
e.printStackTrace();
}
return "";
}
Here,
public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.
More on Android developer reference.

How to pass a parameter through all activities?

I am developing a mobile application where I need the user object to be available through all the activities and I don't want to send it using the Intent from each activity to the other.
Can anyone help me please ?
If you could store it in:
SharedPreferences or
SQLite
I think the SharedPreferences would be much simpler to implement.
Here is an example, how you could create a static function, wich you can access from all your activities:
public class UserCreator
{
public static User getUser(Context context)
{
SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);
//Check if the user is already stored, if is, then simply get the data from
//your SharedPreference object.
boolean isValid = prefs.getBoolean("valid", false);
if(isValid)
{
String userName = prefs.getString("username", "");
String passWord = prefs.getString("password", "");
...
return new User(userName, passWord,...);
}
//If not, then store data
else
{
//for example show a dialog here, where the user can log in.
//when you have the data, then:
if(...login successful...)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "someusername");
editor.putString("password", "somepassword");
editor.putBoolean("valid", true);
...
editor.commit();
}
// Now, if the login was successful, then you can recall this function,
// and it will return a valid user object.
// if it was not, then it will show the login-dialog again.
return getUser(context);
}
}
}
And then from all your activites:
User user = UserCreator.getUser(this);
Just make that object 'public static'.
Then access it in other activities like:
PreviousActivity.userobj
Write a class which extends Application class. And put global parameters there. Those parameters will be valid in application context.

Using Shared Preferences in Android

I have three activities, A, B & C. Where A is a splash Activity and B Contains Login screen which consist of user Id and Password Text Field and one button to login. When I click on login it takes me to the welcome screen shows the user name on screen C.
Here I want to implement Shared Preference so that I can store the userid and password for the user so that user doesn't have to insert the userid and password again & again and after splash screen user directly go to welcome screen.
I read several documents about the shared preference and I came to know that there are two types of shared preference one is activity level and other one is application level.
How can I implement this?
This is relatively easy. You can store the username and password directly in the SharedPreference as follows:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
p.edit().putString("username", username).commit();
p.edit().putString("password", password).commit(); //SECURITY HAZARD: read below...
Then you can retrieve it like this:
String username = p.getString("username", "");
String password = p.getString("password", "");
The issue when doing this is that the password is available globally. You need to have a way to prevent others from viewing it. The way you do this is by encrypting the password when you save it and decrypting it when you load it using a symmetric key. Here's a tutorial on encryption: http://android.voxisland.com/code_examples/How_to_encrypt_and_decrypt_strings.rhtml
Let me know if this helps you at all.
Emmanuel
Write it from Activity A like this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString("YOUR_KEY", "username");
editor.commit();
You can read it afterwards with:
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
String username = p.getString("YOUR_KEY", null);
This is the best way to use Shared preference just call this method
Store shared preference
public static void setDefaults(String key, String value, Context context) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
Call this method and pass argument like this
Classname.setsetDefaults("key","Value",context);
Get Shared Value
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Call this method And pass key
ClassName.getDefaults("Key",Context);
to use shared preference in android
public class SharedPref {
public static void setValue(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getValue(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public static void setAlertDialog(Context mContext,String title,String message)
{
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
and to set and get value from the class use following code
SharedPref.setConfig("key","value",Context);
SharedPref.getConfig("key",Context);
SharedPref.setAlertDialog(Context,"title","Content to print");
Storing username and password is a bad practice instead use JWT. Take a JWT token from your response and then store it in your shared preference. If your API doesn't return any JWT in reply then at least hash your username and password before saving, but it is also unsafe.

Categories

Resources