简体   繁体   中英

Android save user login logout state

I need a little help again with Android SharedPreference.I was earching for a way to save the user state if he is logged in or not..So I did this part, but now the problem is something else.I have a tabhost which include a few tabs and the Login page is started from one of the child Activities.Here is a little example :

TAB1 - TAB2 - TAB3

TAB1 --> ACT1 (child activity of TAB1) ACT1 ---> Login Page.

So I'm using SharedPreferences to get and set the isLoggedIn states,but the problem is that I want to reload the UI when I close the Login Page, so TAB1 can show the new element.

Here is my code for now :

Login Page :

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", true);
        editor.commit();
        this.notifyAll();

and in TAB1 I have this :

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        boolean isLoggedIn = isLogged.getBoolean("isLoggedIn", false);

Any idea how to fix that?

As I understand your problem you want to recongnize when the user logged into on your "LoginActivity" so that you can reload the "TabActivity" right? You can do this by returning a result to the parent activity.

public class StackOverflowActivity extends Activity {

    public static final int LOGIN_REQUEST = 100;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(StackOverflowActivity.this, Login.class);
                startActivityForResult(i, LOGIN_REQUEST);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case LOGIN_REQUEST:
            // TODO implement UI refresh
            Toast.makeText(getApplicationContext(), "I am coming from the login activity!",
                    Toast.LENGTH_LONG).show();
            break;
        default:
            Toast.makeText(getApplicationContext(), "Unexpected request code!",
                    Toast.LENGTH_LONG).show();
            break;
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM