0

I have a loginActivity and a MainActivity

I have used SharedPreferences to store some values in some variables in the loginActivity. Now I want to use these values(They're boolean values) in MainActivity without re=opening MainActivity. How do I do this?

Also, the SharedPreferences are in an onClick method for a button . Thank you!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

I'm assuming that MainActivity starts first, and loginActivity is on top of it in the stack. When loginActivity finishes, you can read the SharedPreferences in MainActivity#onResume.

If you mean that you want to do things in MainActivity while it's in the background or backstack, don't. An activity that is not in the foreground should not be doing any work, and in fact cannot be counted on to exist at all.

StackOverthrow
  • 1,158
  • 11
  • 23
0

There are two ways

1.If you have set the values in shared preferences you can access them from any activity with relevant permissions.

2.Pass when moving from one to another activity and close the other one if need.

        Intent toMain = new Intent(LoginActivity.this, MainActivity.class);
        toMain.putExtra("bool1", "true"); //Optional parameters
        LoginActivity.this.startActivity(toMain);
        //To prevent go back to login
        finish();

then from onCreate of mainActivity

Bundle fromLogin = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("bool1");
    //convert this to boolean
}
fenogy
  • 26
  • 3