Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two activity.

1. MainActivity
2. Login

I want to pass value by sharedpreferences from login to Mainactivity.

I have login text on mainactivity when user click on login text next login activity will open and once user signed from login activity the login activity closed and user will redirected to MainActivity which already opened.

My problem is value passed by sharedpreferences is shown in new Mainactivity but it does not shows in open Mainactivity

my code is below:

Login Page
SharedPreferences prefs = getSharedPreferences("Login", MODE_PRIVATE);
             SharedPreferences.Editor editor = prefs.edit();
             editor.putString("mkw", zabaj);
             editor.apply(); // This line is IMPORTANT. If you miss this one its not gonna work!

             Toast.makeText(Login.this, "Logged In Successfully", Toast.LENGTH_LONG).show();

             finish();



MainActivity

SharedPreferences prefs = getSharedPreferences("Login", MODE_PRIVATE);
       String string = prefs.getString("mkw", null);
       ttl.setText(string);


how to do please tell me.

What I have tried:

online searched but not found similar answer on online
Posted
Updated 18-Mar-23 20:56pm
v3
Comments
David Crow 16-Mar-23 11:52am    
"My problem is value passed by sharedpreferences is shown in new Mainactivity but it does not shows in open Mainactivity"

I'm confused. How can the value be shown but also not be shown?

Where in MainActivity are you retrieving the value from the login activity? In other words, from where are you calling getString() and setText()?

Have you considered using commit() rather than apply()?
MAHESH WAGHELA 17-Mar-23 0:56am    
Yes, but not working.
MAHESH WAGHELA 17-Mar-23 1:00am    
David Crow, Value passed on New MainActivity but not in previous MainActivity. means user press login text from MainActivity and login acitvity open where user put user id and password and closed the login activity by finish() now the user prompted to the previous MainAcitivity where value not shown

1 solution

Perhaps you should use onResume in MainActivity?
override fun onResume() {
    super.onResume()
    SharedPreferences prefs = getSharedPreferences("Login", MODE_PRIVATE);
    String string = prefs.getString("mkw", null);
    ttl.setText(string);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900