My SharedPreferences disappear when I do remove some keys in Android - java

I store some user info, and if it's first time launching the app in SharedPreferences. When user logs out, I remove keys which hold the user info. However, when I do that, it also removes the key where I hold the boolean for app launch for some reason. Why that happens? Source:
On app start:
SharedPreferences prefs = getSharedPreferences("prefs",MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (prefs.getBoolean("isFirstLaunch",true)){
editor.putBoolean("isFirstLaunch",false);
editor.apply();
Intent intentIntro = new Intent(this,TutorialActivity.class);
startActivity(intentIntro);
}
On logout:
SharedPreferences newPrefs = getSharedPreferences("prefs",MODE_PRIVATE);
SharedPreferences.Editor neweditor = newPrefs.edit();
neweditor.remove("authKey");
neweditor.remove("forget");
neweditor.apply();
Intent intent = new Intent(MainActivity.this, LandingActivity.class);
startActivity(intent);

Related

How to use SharedPreferences from differents activities? [duplicate]

This question already has answers here:
sharedpreferences between activities
(3 answers)
Android Shared preferences with multiple activities
(3 answers)
Closed 4 years ago.
I have searched how to use SharedPreferences in Android and ran into a problem.
I save some Strings in the SP and I save the data in Main Activity this way:
in OnCrete function I define:
sp = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = sp.edit();
and then I save the strings to SharedPreferences in the following way:
mail = edmail.getText().toString();
pass = edpass.getText().toString();
color = edcolor.getText().toString();
phone = edphone.getText().toString();
SharedPreferences.Editor editor = sp.edit();
if (mail.equals("") || pass.equals("") || color.equals("") || phone.equals("")||img.getDrawable() == null
)
Toast.makeText(getApplicationContext(), "you have to fill all the fields", Toast.LENGTH_SHORT).show();
else {
editor.putString("mail", mail);
editor.putString("phone", phone);
editor.putString("color", color);
editor.putString("password", pass);
editor.apply();
Toast.makeText(getApplicationContext(), "Signed up", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("img",bitmap);
startActivity(intent);
}
In the second activity I am trying to retrieve the data:
#Override
public void onClick(View v) {
Intent intent=getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("img");
imgv.setImageBitmap(bitmap);
LoadPreferences();
//txtmail.setText(value);
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString("mail", null) ;
Toast.makeText(this,data, Toast.LENGTH_LONG).show();
}
The toast presents the default value instead the real value.
You saved your data in MyPref file which is a different shared preference file as compared to PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
so use
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", 0);
instead of
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
getSharedPreferences("MyPref", 0); will always creates a new file if does not exist whereas the getDefaultSharedPreferences gives you a pref file which is can be used by whole app whit mentioning any name
Change your loading declaration:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
To:
SharedPreferences sp = getApplicationContext().getSharedPreferences("MyPref", 0);

Put username to other activity with sharedpreference

I have value 'username' in MainActivity, get from login session.
How i can put this 'username' to other activity?
I use sharedpreference.
Can you help me? Pleasee
Try this:
To write the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.commit();
To get the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
String username = settings.getString("username", ""); //sets to "" if fails
Or you can pass it through the intent using a bundle:
Bundle bundle = new Bundle();
bundle.putString("username", username);
Intent intent = new Intent(this, JoinChatActivity.class);
intent.putExtras(bundle);
startActivity(this, NewActivity.class);
Try this:
First you initialize the SharedPreferences in Top like this
SharedPreferences sharedPreferences;
after that get the value json like(username) and put the value SharedPreferences
username= obj1.getString("username");
// Using shared preference storing the data in key value pair
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.apply();
And get the value in next activity like this
SharedPreferences pref = getSharedPreferences("MyPref", 0);
String username= pref.getString("username", null);
Pass the value in parameter like this
params.put("username", username);
i think it helps you
Or you can transfer the value using Intent. for example:
This is MainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent (getApplicationContext(), MainActivity.class);
intent.putExtra("userName", username);
getApplicationContext().startActivities(new Intent[] {intent});
}
Other.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_detail);
Intent intent = this.getIntent();
String username = intent.getExtras().toString("userName");
}

Storing and reading DatePicker values from shared preferences not working

I'm trying to allow a user to select a date. This date is then saved into shared prefences, and is used as the countdown date for a countdown timer on the next activity. I am able to save the "name" of the event but not the date, the values returned are just the default.
Storing Date:
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
editor.putString("day", String.valueOf(day));
editor.putInt("month", month);
editor.putInt("day", year);
editor.commit();
Retrieving date:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
String dayEvent = prefs.getInt("day",0);
int monthEvent = prefs.getInt("month",0);
int yearEvent = prefs.getInt("year",0);
String eventString = (dayEvent + "-" + monthEvent+ "-" + yearEvent);
TextView testDate= (TextView) findViewById(R.id.testDate);
testDate.setText(eventString);
return eventString;
The output being 0-0-0 from May 1st 2017, being selected.
I'm not sure if it matters, but these two are in separate classes.
Thanks
Shared Preferences:
SharedPreferences prefs = this.getSharedPreferences("Date_PREF", Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
When you save your preferences you should pass a name :
SharedPreferences prefs = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
// open editor and commit() or apply()
Then to retrieve the data you get the shared preference the exact same way.
You can also use the getDefaultSharedPreferences which are common to all your activities :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
EDIT :
Without using default shared pref
Save
SharedPreferences prefs = getSharedPreferences("DATE_AND_STUFF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();
Retrieve
SharedPreferences prefs = getSharedPreferences("DATE_AND_STUFF", Context.MODE_PRIVATE);
String value = prefs.getString("key", "defaultValue");
Using default shared pref
Save
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FirstActivity.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "value");
editor.apply();
Retrieve
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SecondActivity.this);
String value = prefs.getString("key", "defaultValue");
Hope it will help !

Run activity only once, then always run the main one

As the title says, Scenario is:
On first time using the app, Show Screen A.
Once you are done with screen A, the button will lead to you Screen B.
From now on and forever, the Screen B will always be main "Screen"(Activity?) when you start the app.
I am trying this 2 days and i can't get it.
Somebody please explain a little detailed, or even better throw me a code.rar so i can research it. I'm going crazy with this!!!
Just declare your Activity A as a launcher Activity in your AndroidManifest.xml and inside your Activity A onCreate() you can simply do this
private SharedPreferences mSharedPreferences;
private Editor mEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
mSharedPreferences = getSharedPreferences("yourPrefsFileName", Context.MODE_PRIVATE));
mEditor = mSharedPreferences.edit();
if (mSharedPreferences.getBoolean("isfirstTime", true)) {
mEditor.putBoolean("isFirstTime",false);
mEditor.apply();
}else{
startActivity(new Intent(this, ActivityB.class));
overridePendingTransition(0, 0);
finish();
}
}
All you have to check like this
SharedPreferences prefs = getSharedPreferences("mySHaredpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getBoolean("isfirstTime", true);
if(isFirst) {
Intent intent = new Intent(this, ActivtyA.class);
editor.putBoolean(KEY_IS_FIRST_TIME, false);
editor.commit();
startActivity(intent);
}
else{
Intent intent = new Intent(this, MainActivty.class);
startActivity(intent);
}
public class FirstActivity extends Activity {
public void onCreate(Bundle saved){
super.onCreate();
SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
if (!prefs.getBoolean("firstStart", true)){
startActivity(this, SecondActivity.class);
finish(); // Finish the current one, is like forwarding directly to the second one
}
}
}
Whenever you are done with showing the first activity simple set the shared prefs boolean flag to false:
prefs.getEditor.setBoolean("firstStart", false).commit();
SharedPreferences sp = getSharedPreferences("checking",MODE_PRIVATE);
String data = sp.getString("check", "");
if (data.equals("success")) {
//one time proccess code
//with follow code
SharedPreferences sp= getSharedPreferences("checking",MODE_PRIVATE);
Editor e1 = sp.edit();
e1.putString("check","success");
e1.commit();
} else {
// code for main
Intent intent = new Intent(this, MainActivty.class);
startActivity(intent);
}

Improving login/logout system

I have a login/logout system where by the user logs in either via facebook or our own mysql database.
When users successfully logins in the fullying is saved:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("loggedIn", true);
editor.putString("email", EMAIL);
editor.putString("password", PASSWORD);
editor.putInt("USERID", Integer.parseInt((String) product.get("ProfileID")));
editor.commit();
And then I have a splash page which checks if the user is logged in:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean loggedin = settings.getBoolean("loggedIn", false);
if (loggedin) {
Intent intent = new Intent(this, LoggedIn.class);
startActivity(intent);
} else {
Intent intent = new Intent(this, LogIn.class);
startActivity(intent);
}
And then when a user logs out:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("loggedIn", false);
editor.putString("email", "");
editor.putString("password", "");
editor.commit();
db.clearLists();
db.clearProducts();
Intent intent = new Intent(v.getContext(), Splash.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
v.getContext().startActivity(intent);
This seems to work fine, i.e the user logs out and is sent back to the login page and all their data has been cleared from the app.
However some users are reporting that if they close the app and come back to it they are actually still logged in.
I can not replicate this and so wondering if anyone has any input on how to improve my login/out system to improve it and prevent this.
your code looks ok. But I suppose you can transfer your login to the sqlite db. save them to to db and retrieve login info from db. this is a quick dirty fix;)
Its better to flush your shared preferences while logout and while login check if shared preferences exists then logged in other wise redirect the user to login page.

Categories