Firebase Auth: getCurrentUser from different Activities? - java

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

Related

How can I get username and password from SharedPreferences in Android?

I am trying to recover the username and password to be able to start a session.
These are the users of the sharedPreferences.
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="admin">1234</string>
<string name="user">user0987</string>
</map>
And this is the method
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String user = sp1.getString(userInput.getText().toString(), "User not found");
String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");
if(user.equals(userInput.getText().toString()){
Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}
}
});
This is the code that puts data in SharedPreferences
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = userInput.getText().toString();
String pass = passwordInput.getText().toString();
if(user.isEmpty()){
error.show();
} else if (pass.isEmpty()){
error2.show();
} else{
SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString(user,pass);
Ed.commit();
Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
}
}
});
Please try to use next code when you retrieve data from SP:
SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
String pass = sp1.getString(userInput.getText().toString(), null);
if (pass != null) {
Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
}
You are saving data in form of "user:pasword", so you need to get it the same way, using user name as the key.
You need to add keys for saving for data in SharedPreferences editor.
Currently you are using entered username as key, It can be change according to entered data in edittext, because user will not enter same username every time, but for saving and getting data to/from SharedPreferences we need a specific key.
You can add keys for saving user name and password like following code:
SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putString("user",user);
ed.putString("pass",pass);
ed.commit();
For getting data
SharedPreferences sp1 = getSharedPreferences("data", Context.MODE_PRIVATE);
String userName = sp1.getString("user", "User not found");
String password = sp1.getString("pass", "Password is not correct");
For more info regarding Sharedpref check Official documentation for Save key-value data using SharedPreferences

SharedPreferences return nothing after app restart

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!

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.

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

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