**this code working but you must refresh the Main activity for show the data saved in SharedPreferences how to display data in first time without refresh
**
<code>public class Profile {
private String uid;
private String firstName;
private String lastName;
private String email;
private String phone;
public Profile() {
}
public Profile(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
// Retrieve the data from SharedPreferences
this.uid = sharedPreferences.getString("uid", "N/A");
this.firstName = sharedPreferences.getString("firstName", "N/A");
this.lastName = sharedPreferences.getString("lastName", "N/A");
this.email = sharedPreferences.getString("email", "N/A");
this.phone = sharedPreferences.getString("phone", "N/A");
}
// Method to saveuser data SharedPreferences
public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
// Method to clear user data from SharedPreferences
public void clearDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clear all data
editor.clear();
// Commit the changes
editor.apply();
}
public void loadUserData(Context context) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
if (currentUser != null) {
String userId = currentUser.getUid();
db.collection("users").whereEqualTo("uid", userId).get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot dcprofile = queryDocumentSnapshots.getDocuments().get(0);
this.setUid(dcprofile.getString("uid"));
this.setFirstName(dcprofile.getString("firstName"));
this.setLastName(dcprofile.getString("lastName"));
this.setEmail(dcprofile.getString("email"));
this.setPhone(dcprofile.getString("phone"));
// Save the loaded data to SharedPreferences
this.saveDataShared(context);
}
})
.addOnFailureListener(e -> Log.e("Profile", "Error loading user data", e));
} else {
// Handle the case where the user is not logged in
Log.e("Profile", "User not logged in");
}
}
</code>
<code>public class Profile {
private String uid;
private String firstName;
private String lastName;
private String email;
private String phone;
public Profile() {
}
public Profile(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
// Retrieve the data from SharedPreferences
this.uid = sharedPreferences.getString("uid", "N/A");
this.firstName = sharedPreferences.getString("firstName", "N/A");
this.lastName = sharedPreferences.getString("lastName", "N/A");
this.email = sharedPreferences.getString("email", "N/A");
this.phone = sharedPreferences.getString("phone", "N/A");
}
// Method to saveuser data SharedPreferences
public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
// Method to clear user data from SharedPreferences
public void clearDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clear all data
editor.clear();
// Commit the changes
editor.apply();
}
public void loadUserData(Context context) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
if (currentUser != null) {
String userId = currentUser.getUid();
db.collection("users").whereEqualTo("uid", userId).get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot dcprofile = queryDocumentSnapshots.getDocuments().get(0);
this.setUid(dcprofile.getString("uid"));
this.setFirstName(dcprofile.getString("firstName"));
this.setLastName(dcprofile.getString("lastName"));
this.setEmail(dcprofile.getString("email"));
this.setPhone(dcprofile.getString("phone"));
// Save the loaded data to SharedPreferences
this.saveDataShared(context);
}
})
.addOnFailureListener(e -> Log.e("Profile", "Error loading user data", e));
} else {
// Handle the case where the user is not logged in
Log.e("Profile", "User not logged in");
}
}
</code>
public class Profile {
private String uid;
private String firstName;
private String lastName;
private String email;
private String phone;
public Profile() {
}
public Profile(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
// Retrieve the data from SharedPreferences
this.uid = sharedPreferences.getString("uid", "N/A");
this.firstName = sharedPreferences.getString("firstName", "N/A");
this.lastName = sharedPreferences.getString("lastName", "N/A");
this.email = sharedPreferences.getString("email", "N/A");
this.phone = sharedPreferences.getString("phone", "N/A");
}
// Method to saveuser data SharedPreferences
public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
// Method to clear user data from SharedPreferences
public void clearDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clear all data
editor.clear();
// Commit the changes
editor.apply();
}
public void loadUserData(Context context) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
if (currentUser != null) {
String userId = currentUser.getUid();
db.collection("users").whereEqualTo("uid", userId).get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot dcprofile = queryDocumentSnapshots.getDocuments().get(0);
this.setUid(dcprofile.getString("uid"));
this.setFirstName(dcprofile.getString("firstName"));
this.setLastName(dcprofile.getString("lastName"));
this.setEmail(dcprofile.getString("email"));
this.setPhone(dcprofile.getString("phone"));
// Save the loaded data to SharedPreferences
this.saveDataShared(context);
}
})
.addOnFailureListener(e -> Log.e("Profile", "Error loading user data", e));
} else {
// Handle the case where the user is not logged in
Log.e("Profile", "User not logged in");
}
}
login activity to save data in SharedPreferences by using Profile classe and methods by Btn_login.setOnClickListener if login successful
<code>clearDataShared
loadUserData
saveDataShared
</code>
<code>clearDataShared
loadUserData
saveDataShared
</code>
clearDataShared
loadUserData
saveDataShared
<code> Btn_login = findViewById(R.id.btn_login);
Btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard();
String email,password;
email=String.valueOf((editTextEmail.getText()));
password=String.valueOf((editTextpaswword.getText()));
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
FirebaseUser user = auth.getCurrentUser();
Profile profile = new Profile();
profile.clearDataShared(getApplicationContext());
profile.loadUserData(getApplicationContext()); // Pass context
profile.saveDataShared(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
}
}
});
}
});
</code>
<code> Btn_login = findViewById(R.id.btn_login);
Btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard();
String email,password;
email=String.valueOf((editTextEmail.getText()));
password=String.valueOf((editTextpaswword.getText()));
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
FirebaseUser user = auth.getCurrentUser();
Profile profile = new Profile();
profile.clearDataShared(getApplicationContext());
profile.loadUserData(getApplicationContext()); // Pass context
profile.saveDataShared(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
}
}
});
}
});
</code>
Btn_login = findViewById(R.id.btn_login);
Btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard();
String email,password;
email=String.valueOf((editTextEmail.getText()));
password=String.valueOf((editTextpaswword.getText()));
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Please enter email...", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Please enter password!", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login successful!", Toast.LENGTH_LONG).show();
FirebaseUser user = auth.getCurrentUser();
Profile profile = new Profile();
profile.clearDataShared(getApplicationContext());
profile.loadUserData(getApplicationContext()); // Pass context
profile.saveDataShared(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Login failed! Please try again later", Toast.LENGTH_LONG).show();
}
}
});
}
});
Main activity is for display dara saved in SharedPreferences in “user_prefs”
<code>public class MainActivity extends DrawerBaseActivity{
ActivityMainBinding activityMainBinding;
FirebaseAuth auth;
FirebaseUser user;
FirebaseFirestore db;
Button Btn_Logout,Btn_add;
TextView textView_info;
private TextView datadText;
private static final String TAG = "ProfileActivity";
Profile myprofile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(activityMainBinding.getRoot());
allocateActivityTitle("Main");
datadText = findViewById(R.id.datadtext);
auth =FirebaseAuth.getInstance();
user = auth.getCurrentUser();
Btn_Logout =findViewById(R.id.btn_logout);
textView_info =findViewById(R.id.text_info);
if (user ==null){
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}else {
String infos = String.format("Email: %snUID: %s", user.getEmail(), user.getUid());
textView_info.setText(infos);
// Retrieve the data from SharedPreferences
myprofile = new Profile(this);
// Display the data
datadText.setText(myprofile.toString());
}
</code>
<code>public class MainActivity extends DrawerBaseActivity{
ActivityMainBinding activityMainBinding;
FirebaseAuth auth;
FirebaseUser user;
FirebaseFirestore db;
Button Btn_Logout,Btn_add;
TextView textView_info;
private TextView datadText;
private static final String TAG = "ProfileActivity";
Profile myprofile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(activityMainBinding.getRoot());
allocateActivityTitle("Main");
datadText = findViewById(R.id.datadtext);
auth =FirebaseAuth.getInstance();
user = auth.getCurrentUser();
Btn_Logout =findViewById(R.id.btn_logout);
textView_info =findViewById(R.id.text_info);
if (user ==null){
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}else {
String infos = String.format("Email: %snUID: %s", user.getEmail(), user.getUid());
textView_info.setText(infos);
// Retrieve the data from SharedPreferences
myprofile = new Profile(this);
// Display the data
datadText.setText(myprofile.toString());
}
</code>
public class MainActivity extends DrawerBaseActivity{
ActivityMainBinding activityMainBinding;
FirebaseAuth auth;
FirebaseUser user;
FirebaseFirestore db;
Button Btn_Logout,Btn_add;
TextView textView_info;
private TextView datadText;
private static final String TAG = "ProfileActivity";
Profile myprofile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(activityMainBinding.getRoot());
allocateActivityTitle("Main");
datadText = findViewById(R.id.datadtext);
auth =FirebaseAuth.getInstance();
user = auth.getCurrentUser();
Btn_Logout =findViewById(R.id.btn_logout);
textView_info =findViewById(R.id.text_info);
if (user ==null){
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}else {
String infos = String.format("Email: %snUID: %s", user.getEmail(), user.getUid());
textView_info.setText(infos);
// Retrieve the data from SharedPreferences
myprofile = new Profile(this);
// Display the data
datadText.setText(myprofile.toString());
}
<code>// @Override
// protected void onResume() {
// super.onResume();
//
// // Retrieve the data from SharedPreferences
// myprofile = new Profile(this);
// // Display the data
// datadText.setText(myprofile.toString());
// }
</code>
<code>// @Override
// protected void onResume() {
// super.onResume();
//
// // Retrieve the data from SharedPreferences
// myprofile = new Profile(this);
// // Display the data
// datadText.setText(myprofile.toString());
// }
</code>
// @Override
// protected void onResume() {
// super.onResume();
//
// // Retrieve the data from SharedPreferences
// myprofile = new Profile(this);
// // Display the data
// datadText.setText(myprofile.toString());
// }
tryed onResume no working
changin order in login Activity
You are not calling editor.apply() in your saveDataShared() method.
Your code:
<code>public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
</code>
<code>public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
</code>
public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
}
Correct way:
<code>public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
editor.apply();
}
</code>
<code>public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
editor.apply();
}
</code>
public void saveDataShared(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
// Put the data into SharedPreferences
editor.putString("uid", this.uid);
editor.putString("firstName", this.firstName);
editor.putString("lastName", this.lastName);
editor.putString("email", this.email);
editor.putString("phone", this.phone);
editor.apply();
}
New contributor
vAayush3301 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.