I'm new to android and java. I tried SharedPreferences to manage session. Once I login into screen I writing below code.
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", true);
editor.commit();
When I closed the app and started again, it directly going to home screen without asking the credentials.
I dont know where to write these below lines:
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
I want to clear the SharedPreferences even if the app closed directly. I tried with finalize but it didn't worked.
EDIT:
I add below code to my file. It is working but giving error.
code:
protected void onStop() {
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", false);
editor.commit();
}
Error:
android.app.SuperNotCalledException: Activity {com.ec.testtab/com.ec.testtab.Tabs} did not call through to super.onStop()
Better to set prefs to false at your app closed. and when you come back again you just need to check this prefs value true or false.
false--- means not login
true---- means logined
I have handeled such things inside these two methods of activity they will be called in your case too so give a try:
#Override
protected void onResume() {
super.onResume();
// Start Logging
}
#Override
protected void onPause() {
super.onPause();
// End Logging
}
If you don't want to store shared preferences while your app is getting closed, you should clear your shared preferences every time your app is getting started, so that no previous shared preferences will be there while doing your app's further processes.
Once user logged-in into app with valid credentials then only changed share preferences login value to true.
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", true);
editor.commit();
And every time on Oncreate just check "login" value to determine whether user is already logged-in or not.
You can add this lines of code
SharedPreferences prefs = getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("login", false);
editor.commit();
when your app starts before fetching the username and password from the preferences. So that every time you start the app it will show login page.
Sharedpreferences is used for persistent storage, if u don't need store information for next launcher, use public static boolean isLogin maybe an easy way:
public static boolean sIsLogin = false;
...
if(doLogin()){
sIsLogin = true;
}
...
When u closed the app and started again, sIsLogin is false.
Related
I am saving some data to SharedPreference from a fragment and want use these data in other fragments. But I want to perform fragment transaction only if SharedPreferences are saved successfully, otherwise, other fragments would not be able to retrieve data (since using those SharedPreference values to retrieve data).
My code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
... ... ... ... ... ... ... ... ...
public void setSharedPref(String key, String val) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, val);
editor.commit();
}
public String fetchSharedPref(String key) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String val = sharedPref.getString(key, Constant.SHARED_PREF_DEFAULT_MSN);
return val;
}
}
How can I be sure that SharedPreferences are saved successfully?
Is there any way to implement a callback that will be invoked only if SharedPreferences saved successfully?
From the docs.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Then go and check commit() method here.
Return type: boolean
Description: Returns true if the new values were successfully written to persistent storage.
Find the solution :
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("Your Key", "Your value");
boolean savedOrNot = editor.commit();
if(savedOrNot){
// Successfully saved
}else{
// Not saved
}
Form Documentation
apply()
This saves your data into memory immediately and saves the data to
disk on a separate thread. So there is no chance of blocking the main
thread (your app won’t hang).
It is the preferred technique but has only been available since
Gingerbread (API 9, Android 2.3).
commit()
Calling this will save the data to the file however, the process is
carried out in the thread that called it, stopping everything else
until the save is complete. It returns true on successful completion,
false on failure.
Use commit() if you need confirmation of the success of saving your
data or if you are developing for pre-Gingerbread devices. commit()
has been available since API 1
so your can check status at editor.commit();
commit() returns true if the save works, false otherwise.
commit() returns true if the save works, false otherwise.
You can alter your method as follows.
public boolean setSharedPref(String key, String val) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, val);
return editor.commit()
}
Difference between apply and commit https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
The editor.commit() will return boolean value , which will let you know if data has been saved.
If you would like to analyze all the data saved in shared preferences and sqlite ,then i would recommend using facebook stetho
Its a debug bridge for android , you can check all of your shared preferences data and sql databases for debugging.
I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.
You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
//save the value
prefs.edit()
.putInt("nameOfTheValue", theValue).apply();
// get the data
prefs.getInt("nameOfTheValue", aDefaultValue);
You should save them as User SharedPreferences in onDestroy method.
public void onDestroy() {
super.onDestroy();
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//set the sharedpref
Editor editor = settings.edit();
editor.putInt("FIRST_INT", firstIntValue);
editor.putInt("SECOND_INT", secondIntValue);
editor.commit();
}
And then you can get them back wen needed:
SharedPreferences settings;
settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
//get the sharepref
int firstInt = settings.getInt("FIRST_INT", 0);
int secondInt = settings.getInt("SECOND_INT", 0);
If you can help me I will be very grateful,
i want to launch an intent only in first load of my android application and save same settings. To save my settings I use SharedPreferences :
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", false);
edit.commit();
Thanks a lot.
you can do something like this
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
if(preferences.getBoolean("isFirstRun", true)){
edit.putBoolean("isFirstRun", false);
edit.commit();
//Do your stuff for first Run
}else {
}
In your activity A, you should check in your shared preference like:
if(!pref.getBoolean("isFirstRun", false)){
//Load activity B
// put your code for updating shared pref as you mention above.
}else{
//Load activity C
}
I have a few data I saved in SharedPreference. WHen a button is clicked, the user is logged out and the sharedPreference is cleared by calling pref.clear() ad pref.commit(). When a user tries to log back in, the editor is called to commit() but it wouldn't save the new values. Any suggestions why shared preference is not saving after clearing is done?
Clearing part:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor sa = prefs.edit();
sa.clear();
sa.commit();
re-adding part:
editor.putString("bucket", bucket);
editor.putString("profileid", profileid);
editor.putString("username", user);
editor.putString("password", pass);
editor.commit();
CLOSED: answer in the bottom but for anyone else that is looking for an answer, i accepted the answer
how are you initializing editor (whitch I asume is SharedPreferences.Editor). I use the following to get editor.
SharedPreferences settings = getActivity().getSharedPreferences("a_string", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
I do this the same way for clearing and saving my data.
pleas post more information if this dose not help.
Actually my fault, there was a typo while I was initiation my preferences. Sorry folks!
Let me show you a working example of how to add/read/remove data from SharedPeferences.In your Activity for adding some data into SharedPreferences
SharedPreferences prefs = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("bucket", bucket);
editor.putString("profileid", profileid);
editor.putString("username", user);
editor.putString("password", pass);
editor.commit();
You would want to do the above when is user is logged in successfully.Now when the user logout, inside your onClickListener for logout Button
SharedPreferences settings = getApplicationContext().getSharedPreferences("yourPrefName",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
So in your Activity's code you should check if SharedPreferences values are already set.If they are set, then you can redirect user to the home screen without having to login again.
I am getting trouble in making only one time login... My aim is first user gets login screen.. If he is new user he will register and then login...from then when ever user starts the application he should directly redirect to main activity that is to skip the login page..please friends help me out from this problem..please post me any tutorials or any code...please tell me how to modify in manifest file also...
I am using like this in login activity but i didn't achieve my task.
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
editor.putString("register","true");
editor.commit();
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true"))
// redirect to next activity
else
// show registration page again
Implement your SharedPreferences this way:
Boolean isFirstTime;
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(Splash.this);
SharedPreferences.Editor editor = app_preferences.edit();
isFirstTime = app_preferences.getBoolean("isFirstTime", true);
if (isFirstTime) {
//implement your first time logic
editor.putBoolean("isFirstTime", false);
editor.commit();
}else{
//app open directly
}
check it here
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
A very good example of session management in android app.
Use SharedPreferences. contains which tell an key is present or not in SharedPreferences. Change your code as:
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
if(pref.contains("register"))
{
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true")){
redirect to next activity
}else{
//first time
editor.putString("register","true");
editor.commit();
/// show registration page again
}
}
else{ //first time
editor = pref.edit();
editor.putString("register","true");
editor.commit();
/// show registration page again
}
You can visit my blog
http://upadhyayjiteshandroid.blogspot.in/2013/01/android-working-with-shared-preferences.html
hope you will get the answer and understanding clearly
Boolean flag;
SharedPreferences applicationpreferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = applicationpreferences .edit();
flag = applicationpreferences .getBoolean("flag", false);
if (flag) {
///second time activity
}else{
//first time
editor.putBoolean("flag", true);
editor.commit();
}
Check out the Session Management in Android which shows you the way how you can manage the login if user is already logged into the application or not. And switch the user accordingly.
Hope this will help you.
1.for storing in stored preferences use this
SharedPreferences.Editor editor = getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
2.for retrieving the same use
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);