androidandroid-activitysharedpreferencesswitching

Android shared preferences conditional activity switching


I have an Android app which I use to register users on my web site. My first task is to register a user if my shared preferences file shows there is no registered user information.

If my app has a registered user, I provide the following code to simply and automatically switch to a "homepage" activity:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin);
        
        if( USERPREFERENCES.getString(USERPREFERENCES_USERMAIL, "")  == null && USERPREFERENCES.getString(USERPREFERENCES_USERID, "") == null && USERPREFERENCES.getString(USERPREFERENCES_USERNAME, "") == null){
            //setContentView(R.layout.signin);
            Toast.makeText(SignIn.this, "testing...", Toast.LENGTH_LONG).show();
        }else{
            Intent intent   =   new Intent(SignIn.this, Confirmed.class);
            startActivity(intent);
        }
... other code

So, from my default activity, signin.java, the app will either switch to the Confirmed activity or stay on and display the signin activity.

My problem is, when the system works and I get switched to the the Confirmed activity, I provide a logout onclick listener which is below:

 signout.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //USERPREFERENCES.cl
                Toast.makeText(Confirmed.this, "signout responding!", Toast.LENGTH_LONG).show();
                USERPREFERENCES.edit().clear().commit();
            }
        });

It responds and clears all my shared preferences variables. But, when I use my menu to manually switch to the sign-in activity, I still get switched back to the Confirmed activity.

This happens even though I can confirm the variables are empty.


Solution

  • This hardly ever will be true:

    USERPREFERENCES.getString(USERPREFERENCES_USERMAIL, "")  == null
    

    What if you use this instead?

    if( USERPREFERENCES.getString(USERPREFERENCES_USERMAIL, null)  == null && USERPREFERENCES.getString(USERPREFERENCES_USERID, null) == null && USERPREFERENCES.getString(USERPREFERENCES_USERNAME, null) == null){
        //setContentView(R.layout.signin); TRY TO AVOID DOING THIS THING!!!!!
        Toast.makeText(SignIn.this, "testing...", Toast.LENGTH_LONG).show();
    }else...
    

    Also, as a recommendation... instead of being switching between activities... what if you create just a Signing.java activity and put a ViewFlipper in its layout. That way your app will be not only faster but also easier to maintain.