SharedPreferences return nothing after app restart - java

i save my token in Shared Preferences with this Set Token method
public static void setToken(Context ctx, String token) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_TOKEN, token);
editor.apply();
}
and get token with this get Token method in all my project
public static String getToken(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_TOKEN, "456");
}
my problem is when app is restarted, get Token method return "456"
home activity token log :
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjBkM2JlODBlMTg4Mzc4NTNjY2VjYjU2Nzg1NzAxYjNhM2NhZGJiOWFhYTZjYWIwNDQ3YjA4MzJmMzRkNmMxMzM5MzAyMWE2OWQ4NDk2ZTY1In0.eyJhdWQiOiIxIiwianRpIjoiMGQzYmU4MGUxODgzNzg1M2NjZWNiNTY3ODU3MDFiM2EzY2FkYmI5YWFhNmNhYjA0NDdiMDgzMmYzNGQ2YzEzMzkzMDIxYTY5ZDg0OTZlNjUiLCJpYXQiOjE1NjAzMTY5MTQsIm5iZiI6MTU2MDMxNjkxNCwiZXhwIjoxNTkxOTM5MzE0LCJzdWIiOiI1Iiwic2NvcGVzIjpbXX0.RovbkU1XXCuOcUvAzutW9Btm64BlYc8jAZTTeiPue43-YUMv2Ftr2m40I6yVH0JPdCGHwbtIruJRHeM8fx1ua4pryBQIxgdCvB-S5FiioOPR_zrG-II_pEquUQoz3wEpxmwG1KDmYOWfENA7El6v8e3mnyg54o9ikcYCFLgoV3V5kcdhX4RZRWeRE8ED76m1YhImjuIAkSV88tmtrzt1E7dWM_lfWDLGOsrPnOLFdzEGDozGHcMU6D5-qN9CroBGzrlLD4ngvk1yV1cypSLgsM9yuJ3b9MJJhcs5v_mrm5McT6aipcM6ghKdClGF7_SBAjREPJGxPD7-KY5sH4L9NkpsxH4SQL9fxKpE_Z2B_PCKVaCGtSBQ0E1dURFIkJfUWhFsRZea1DBXQkZTDcAnxj9WA2ZDqWe_Ve-fPDyhmnfObHfeJ0NRtm-Wgq6R-F5PwlF_SjxgrhXhKsAd4knvvkP-o06e_d3fb-8mUedmQQroI9VXci6kE5gJhqUWjX5OpCLWBCFY12Y5Vntg2R-G_sLPJXewkM7TcXlc381V212bJElFThgurWfm4zRfWA5L8VV8d_xms3f852rOg2z6xh0dNt5zeqp3b8IS68k1wTzBPGobJZSvr5ZDd_xZYpJREsDeLh8Osr7hP3V3zUWIMGdEyKUL3ITCL7FMAtj9VFA
After restart :
token=456

Simple mistake, you have to replace this line
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
to below one
SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, context.MODE_PRIVATE).edit();
Where KEY_PREFS_NAME is the name of your preference

Try this to save it:
public void saveToken(String token){
SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TOKEN, token).apply();
}
and this to get back:
public String getToken(){
SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
return sharedPreferences.getString(TOKEN, "")
}
Hope it helps!

Related

Refreshing SharedPreference to retrieve fresh data when user loggedin

I have been successful in writing a code to retrieve and store user data using sharedpreference. However as long as the user is loggedin any changes made to the data does not show unless user logout.
Here is my code:
public class SharedPrefManager {
private static final String SHARED_PREF_NAME = "my_shared_preff";
private static SharedPrefManager mInstance;
private Context mCtx;
private SharedPrefManager(Context mCtx) {
this.mCtx = mCtx;
}
public static synchronized SharedPrefManager getInstance(Context mCtx) {
if (mInstance == null) {
mInstance = new SharedPrefManager(mCtx);
}
return mInstance;
}
public void saveUser(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("id", user.getId());
editor.putString("email", user.getEmail());
editor.putString("firstname", user.getFirstName());
editor.putString("lastname", user.getLastName());
editor.putString("companyname", user.getCompanyName());
editor.putString("address1", user.getAddress1());
editor.putString("city", user.getCity());
editor.putString("state", user.getState());
editor.putString("postcode", user.getPostcode());
editor.putString("country", user.getCountry());
editor.putString("phonenumber", user.getPhonenumber());
editor.putString("status", user.getStatus());
editor.putInt("currency", user.getCurrency());
editor.putString("credit", user.getCredit());
editor.putString("language", user.getLanguage());
editor.putInt("email_verified", user.getEmail_verified());
editor.apply();
}
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getInt("id", -1) != -1;
}
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getInt("id", -1),
sharedPreferences.getString("email", null),
sharedPreferences.getString("firstname", null),
sharedPreferences.getString("lastname", null),
sharedPreferences.getString("companyname", null),
sharedPreferences.getString("address1", null),
sharedPreferences.getString("city", null),
sharedPreferences.getString("state", null),
sharedPreferences.getString("postcode", null),
sharedPreferences.getString("country", null),
sharedPreferences.getString("phonenumber", null),
sharedPreferences.getString("status", null),
sharedPreferences.getInt("currency", -1),
sharedPreferences.getString("credit", null),
sharedPreferences.getString("language", null),
sharedPreferences.getInt("email_verified", 1)
);
}
public Emails getEmails() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new Emails(
sharedPreferences.getString("subject", null),
sharedPreferences.getString("message", null)
);
}
public void clear() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
}
Is there a way to add a background refresh activity to SharedPreference whereby code retrieves and update stored data without logging the user out?
SharedPreferences already does this. Instead of reading out everything from the SharedPreferences in getUser and getEmails, you should read an individual preference when you need its value. Whenever you read a value from the SharedPreferences object, you'll get its latest value every time.
One way you might do this is by getting rid of your SharedPrefManager class, give your User class a SharedPreferences member, and implement User.getId to call sharedPrefs.getInt("id") and so on.
You can register a listener using sharedprefs. registerOnSharedPreferenceChangeListener.
Also you are writing a lot of boilerplate code to read/write on shared preferences. You can use something like this.

Firebase Auth: getCurrentUser from different Activities?

I have an app with a login screen. Now, i just want to get the DisplayName of the user which is signed in in another Activity. How can I get this name?
Use getCurrentUser():
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, getEmail or etc
String name = user.getDisplayName();
Log.d("TAG" + name) // the name ...
}
https://firebase.google.com/docs/auth/android/manage-users#get_the_currently_signed-in_user
Using SharedPreferences or Bundle you can get it.
private void onAuthSuccess(FirebaseUser currentUser) {
userId = currentUser.getUid();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
if (currentUser.getDisplayName() != null){
editor.putString("userName", currentUser.getDisplayName());
} else if (currentUser.getEmail() != null){
editor.putString("useremail", currentUser.getEmail());
}
editor.putString("userId", currentUser.getUid());
editor.commit();
}
Another Activity you can get it below
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
String displayUser = sharedPref.getString("userName",null);
String displayEmail = sharedPref.getString("useremail",null);

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

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 !

Store and retrieve strings in ArrayAdapter with SharedPreferences

I need to save and retrieve two strings in an ArrayAdapter of my NavigationDrawer.
First of all. I declared this:
private static SharedPreferences prefs;
then in the getView() method
SharedPreferences.Editor editor = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE).edit();
editor.putString("username", NameStr);
editor.putString("photo", urlProfile);
editor.commit();
In this way i'm going to save the strings i need. But i'm not exactly sure because i never use the Sharedpreferences in an Adapter. How can i retrieve the datas? Where have i to put it? thanks
EDIT:
to achieve the strings i wrote in getView()
Intent intent = ((Activity) context).getIntent();
NameStr = intent.getStringExtra("username");
urlProfile = intent.getStringExtra("photo");
where the two strings comes from another activity.
EDIT2: SOLUTION
Dexter got the solution and it works perfectly:
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS",context. MODE_PRIVATE);
if(sharedPreferences == null) return;
NameStr = sharedPreferences.getString("username", "");
urlProfile = sharedPreferences.getString("photo", "");
SharedPreferences.Editor editor = sharedPreferences.edit();
Intent intent = ((Activity) context).getIntent();
if(NameStr == null || NameStr.equals("")) {
NameStr = intent.getStringExtra("username");
editor.putString("username", NameStr);
}
if(urlProfile == null || urlProfile.equals("")) {
urlProfile = intent.getStringExtra("photo");
editor.putString("photo", urlProfile);
}
editor.apply();
all of this in the Adapter construction!
You can retrieve the data using :
SharedPreferences sharedPreferences = context.getSharedPreferences("MYPREFS", context.MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String photo = sharedPreferences.getString("photo", "");
Also prefer using editor.apply()

Categories