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.
Related
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!
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);
I have 2 Activities, Authentication and Mainpage.
In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
}
In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
finish();
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
}
The problem here is when I click the logout button, I just kept redirecting to Mainpage.
The problem is that you are finishing the activity before starting the Intent..That is why it shows MainPage when the logout() is called..Instead, you will have to finish the activity after the intent has been called.
Thus replace your code as follows
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
finish(); /****<------Moved to here---****/
}
UPDATE
Since you are adding onClick attribute in your xml for the button and you are getting an error
java.lang.IllegalStateException: Could not find method logOut(View) in
a parent or ancestor Context for android:onClick attribute defined on
view class android.support.v7.widget.AppCompatButton with id
'logoutButton'
Replace your function as follows
void logOut(View v){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
finish(); /****<------Moved to here---****/
}
However, I dont think it's a good idea to solve this way. You should implement onClickListener inside your adapter or your fragment.
Try this, hope it helps
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.commit(); // to apply the changes
finish();
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
}
Replace your this line of code
blockEdit.apply();
with
blockEdit.commit();
Followed by your activity calling intent.Hope it helps.
Just reset your SharedPreferences KEY logged_in value to false using blockEdit.putBoolean("logged_in", false) and commit.
Try this:
void logOut(View view) {
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
// Set logged_in value to false
blockEdit.putBoolean("logged_in", false);
blockEdit.commit();
// Start Authentication
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
// Finish MainPage
finish();
}
#. Best practice is to create a common class for session management and use this from anywhere in your application as per your needs.
Crate a SessionManager class like below:
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
Context context;
// Shared Preferences
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MY_APP";
private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";
private static final String KEY_USER_ID = "USER_ID";
private static final String KEY_USER_EMAIL = "USER_EMAIL";
private static final String KEY_USER_USERNAME = "USER_USERNAME";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn() {
return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void setUserId(int id) {
editor.putInt(KEY_USER_ID, id);
editor.commit();
}
public int getUserId() {
return sharedPreferences.getInt(KEY_USER_ID, 0);
}
public void setUsername(String username) {
editor.putString(KEY_USER_USERNAME, username);
editor.commit();
}
public String getUsername() {
return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
}
public void setEmail(String email) {
editor.putString(KEY_USER_EMAIL, email);
editor.commit();
}
public String getEmail() {
return sharedPreferences.getString(KEY_USER_EMAIL, "default#gmail.com");
}
}
USE:
LOGIN:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);
// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
LOGOUT:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);
// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
Hope this will help~
Put finish() here in the code of yours
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
UPDATE
I went through your code and found a small mistake in it :
In your OnCreate method you are using :
SharedPreferences blockSession = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(!isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
Mistakes :
You are getting your sharedPreference value in on create method But when you are clearing sharedPreference on logout it doesn't have any shaved sharedPreference value . so it takes false as default value as you mentioned here :
boolean isLoggedIn = blockSession.getBoolean("logged_in", false); // false is default value.
And you if conditioned is always true because you have false value every time you logout.
Solution :
change if condition as follows :
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
Try it.
SharedPreferences mySPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mySPrefs.edit();
editor.remove(String key);
editor.apply();
I have this inside myMainActivity:
public void sendNotificationIfTimeEnd01() {
Intent intent01 = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.google.de/?gws_rd=ssl"));
PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_stat_notification);
builder.setContentIntent(pendingIntent01);
builder.setAutoCancel(true);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
builder.setContentTitle(gamesJuliToStringArray[0]);
builder.setContentText("Ready");
builder.setSubText("click for google");
NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
I call it inside my fragment like this:
if (diffDays <= 0) {
String diffDaysAvailable = "ready";
((TextView) android.findViewById(R.id.readyLeft)).setText(diffDaysAvailable);
((TextView)
activity.sendNotificationIfTimeEnd01();
Log.d("MyApp", "notification 1");
}
I basically get a sample notification if diffDays <= 0.
That works so far.
The problem is that the notification always pops up, when I restart the app.
I googled and read that one should use shared preferences to solve this issue.
(Not experienced with it).
I have this so far:
final SharedPreferences sharedPreferences = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
// push notification once time is up
final String notification01 = sharedPreferences.getString("notification01", "not01");
But have no idea how to continue and solve this issue.
Do something like this:
if (diffDays <= 0) {
final SharedPreferences sharedPreferences = getActivity().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
final boolean notification01 = sharedPreferences.getBoolean("notification01", false);
if (!notification01) {
String diffDaysAvailable = "ready";
((TextView) android.findViewById(R.id.readyLeft)).setText(diffDaysAvailable);
activity.sendNotificationIfTimeEnd01();
Log.d("MyApp", "notification 1");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("notification01", true);
editor.apply();
}
}
Before sending any notification, this will check if the boolean is false or not. If it is false, then send the notification and set that boolean true, else nothing.
This line initializes your SharedPreference with the name you provided and which will remain Private to your app
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("YOUR_PREFERENCE_NAME", Context.MODE_PRIVATE);
Call this method when you want a boolean data is stored in preference which is associated with a key (a string literal).
public void setValue() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("your_key", true);
editor.commit();
}
With this method you can check if you have already put a true value in your preference with a key.
public boolean isValueExists() {
boolean value = sharedPreferences.getBoolean("your_key", false);
return value;
}
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()