Shared Preferences data retrieve not working must refresh activity to get data

**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
**

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>clearDataShared
loadUserData
saveDataShared
</code>
<code>clearDataShared loadUserData saveDataShared </code>
clearDataShared
loadUserData
saveDataShared 
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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”

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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());





        }
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật