Cannot read key from SharedPreferences - android

So basically I have an activity (SplashActivity) that serves as a splash screen. It reads a key named username from the application's SharedPreferences, then if it finds the key, starts HomePage activity. Otherwise it starts LoginActivity. When the login is successful in LoginActivity, I am storing the username and password via this code:
SharedPreferences prefs = LoginActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
The login page also has an autocomplete feature for the password field. This is how I am reading the password:
String password = this.getPreferences(MODE_PRIVATE).getString("password", "");
And I get the stored password. However, when I restart the app and run SplashActivity I can't read the password despite using the exact same code as above. Is there something wrong I am doing here?

Quoting the JavaDocs for getPreferences():
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.
(emphasis added)
So, SplashActivity cannot read a value written to the private preferences of LoginActivity.
You probably want to switch to getSharedPreferences(), where you provide your own name that can be shared between the two activities.

Related

Android One-time Login screen using SharedPreferences

I am Wondering about One-time screens... I know, I should use something like SharedPreferences or stuff like that.
If someone has a simple solution for one-time login screen. And a little example.
My login contains: weight, name , height, age and gender (spinner)
You can take a look at Android User info and Sign in :
https://developer.android.com/training/sign-in/index.html
Or you can use login with Facebook API.
Otherwise, I would use Shared prefs.
Create a shared prefs file
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
This will create a private file for the current activity. You can use MODE_WORLD_READABLE and MODE_WORLD_WRITABLE if it fits your needs.
You can also provide a file name as the first parameter if needed :
SharedPreferences sharedPreferences = getPreferences("com.example.stackoverflow.myfile", Context.MODE_PRIVATE);
Write a shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USERNAME", "test");
editor.commit();
You can put any primitive type : int, string, boolean, etc.
It is a key/value set. the key string "USERNAME" will then have a value of "test".
Read shared pref
String username = sharedPreferences.getString("USERNAME", "NO NAME");
The second parameter is a default value to use if the key "USERNAME" didn't get any value.

Retrieving SharedPreferences

I'm working with an android application, and when my application is open I want to log in. I'm using shared preferences for saving data.
How can I control three cases: if his credentials are null, if that user exists and does not have to register and save his credentials again and also if username and password he entered is correct and is the same with them he used when entered for the first time.
Use this code to retrieve values from sharedPreferences.
SharedPreferences sharedPref ;
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int status=sharedPref.getInt("status",0);
if(status==1){
//do something here you want to do
}else if(status==2){
//do something here you want to do
}
Read the documentation here http://developer.android.com/reference/android/content/SharedPreferences.html
Also check this http://www.tutorialspoint.com/android/android_shared_preferences.htm

How to have android app remember user data/profile?

Making a app that asks user to create a profile, wondering where I should get started in having the app remember this data user inputs? Any tutorials or suggestions would be appreciated.
Thanks,
Grant
I suggest you use SharedPreferences, unless you have a lot of information to store.
After the user successfully logged in, store his information in your Preferences.
For example, to store the username :
private SharedPreferences mPreferences;
mPreferences = getSharedPreferences("User", MODE_PRIVATE);
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("username", your_user_name);
editor.commit();
Each time the user accesses the login activity, you can check if the username is already stored in the preferences :
if (mPreferences.contains("username")) {
// start Main activity
} else {
// ask him to enter his credentials
}
When the user logs out, don't forget to delete the username key from your preferences :
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear(); // This will delete all your preferences, check how to delete just one
editor.commit();
Insert the data to a SQLite database or use a plain file. The former is recommended for big apps.
Checked out SharedPreferences. Some examples here: SharedPreferences Tutorial
If you only have one user at once and just need to store simple user data like user name, email, id, you can store string/int/... format data in it. Or if you have server for storing user data, you can store credentials in SharedPreference and use the credentials to get data from your server.

Does SharedPreferences work in Eclipse emulator?

I am attempting to save a user id using SharedPreferences. Do values saved as SharePreferences persist across all Activities in my application so I can access the userid from any application? Below is my code for saving the userid.
userid = result.substring(3, result.length());
Log.d("userid at onpostexecute", userid);
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); // to update userid
editor.putString("userid", userid);
editor.commit();
And here is the code for accessing the userid from the SharedPreferences in another activity.
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // to access userid
String userid = prefs.getString("userid", "");
Log.d("shared prefs userid", userid);
What is strange is that the above code is in my onCreate method but it doesn't show up in the Logcat even though other log data is displayed before and after this code. So is there something wrong with my code that I can't even get it to display in my logcat? I can't even tell if it is being updated.
Values saved as sharedPreferences can be shared between activities if you tell it to. Right now you are creating a preference that is only accessible to that same activity. You need to use:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
Like this you are creating a sharedPreference between your application. There is a lot of explanation on the topic in the accepted answer to another question. Link to question
As discussed in the answer the way you are using to save the preference will only work in the same activity that saved it.
I assume you mean can you access them from any Activity, yes, they do persist even when you leave your app and come back. From the Docs
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
If this Log.d("userid at onpostexecute", userid); doesn't even show up then I would put a breakpoint there and make sure you have a value for userid. I would also check your logcat filters to make sure that you are getting all logs. Just make sure that the type in the spinner is set to "verbose" just to be sure

Shared Preference problem in android app

in my app the first activity is a sign in page. In the edit boxes i am typing the user name and password. Those values are been move to an api and in return i am getting the userid from the server as an xml file.
I am parsing the xml file and storing the value in shared preferrence as follows
SharedPreferences.Editor IdEditor = Id.edit();
IdEditor.putString("useridValue", chap.getid());
IdEditor.commit();
And in the next time when the user opens the app i want to check whether it is already signed i or not. How to check this using the value stored in Shared preference
is your Id class extending SharedPreferences ?
maybe
String userId = Id.getString("useridValue");
If your preference is stored in the default preference then you can
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userId = prefs.getString("useridValue");
on a side note you shouldn't really use a capital I on the IdEditor variable it should probably be idEditor
Check whether this entry already exist in shared preference, using:
id.containskey("useridvalue")

Categories

Resources