SharedPreference - clearing and readding - android

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.

Related

Get last login details without webservicing

need an idea to get last login details(DATE OF LAST LOGIN) on login without webservicing concept
Store Last login date into SQLLITE database when you need last login detail fetch this values from SQLLITE database.
instead of sqlite use SharedPreferences
you will have to create an object of shared preference and an editor
it will be similiar to this:
SharedPreferences sp;
SharedPreferences.Editor ed;
ed=sp.edit();
ed.putBoolean("username",username);
ed.commit(); //**DONT FORGET TO COMMIT**
sp = getSharedPreferences("MenuData", MODE_PRIVATE);
if(!sp.contains(null))
{
username=sp.getBoolean("username",defaultvalue);// you need to add an default value
if(username.equals("admin")){
//do watever u like
}
}
soloved the problem,
setting the value before even putting;
min=c.get(Calendar.MINUTE);
seconds=c.get(Calendar.SECOND);
SharedPreferences prefs1 = getSharedPreferences(
"DATE", MODE_PRIVATE);
datee = prefs1.getString("SUBDATE", null);
DATE1.setText(datee);
SharedPreferences.Editor editor = getSharedPreferences("DATE", MODE_PRIVATE).edit();
editor.putString("SUBDATE", min+" "+seconds+" ");
editor.commit();

Where to clean SharedPrefererences when user closed app directly?

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.

How to display only one time Login and then after start application directly in android

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);

Why using SharedPreferences.Editor object to modify data rather than SharedPreferencesInstace.edit()?

I check the SharedPreferences example and curious about the code for data modification in SharedPreferences:
SharedPreferences preferences = getSharedPreferences (name, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Greeting", "Welcome to sharedpreferences!");
editor.commit();
Log.d("shared preferences", preferences.getAll().toString());
I wonder why the lines of second to fourth:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Greeting", "Welcome to sharedpreferences!");
editor.commit();
can't rewrite as:
preferences.edit().putString("Greeting", "Welcome to sharedpreferences!");
preferences.edit().commit();
LogCat does not show up any key pair values after this change. It seems not feasible to write with this way. Just wonder why it necessary to declare an SharedPreferences.Editor object rather than directly called from the SharedPreferences class?
The source code of SharedPreferences:
http://www.java2s.com/Open-Source/Android/UnTagged/dexandroid/android/content/SharedPreferences.java.htm
The link you gave is for documentation and interface, not the actual implementation of the SharedPreferences you got.
You are not promised to get the same editor each time you call edit(), so calling commit on editor will not commit the changes in the object preferences.edit() since it might be a separate object.
In your example:
SharedPreferences.Editor editor = preferences.edit();
// ^object #1
editor.putString("Greeting", "Welcome to sharedpreferences!");
//^object #1
editor.commit();
//^object #1
preferences.edit().putString("Greeting", "Welcome to sharedpreferences!");
// ^object #2
editor.commit();
//^object #1
You can rewrite it as:
SharedPreferences preferences = getSharedPreferences(name, MODE_PRIVATE);
preferences.edit()
.putString("Greeting", "Welcome to sharedpreferences!")
.commit();
Log.d("shared preferences", preferences.getAll().toString());

how to empty the sharedpreferences storage in android?

i'm using sharedPreferences to store username and password .. but i need to make log off, how can i remove the data od username and password ?
You have to use the SharedPreferences Editor object to do it. You can follow the next example:
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("username_field");
editor.remove("password_field");
editor.commit();
Just in case you want to clear the entire preference too, useful if you've only got the users details in the preference, and you want to remove all of that, you Can use.
SharedPreferences preferences =
getSharedPreferences("PREFERENCE",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

Categories

Resources