[Solved] How to use SharedPreferences to change view visibility in login and logout


To place info into SharedPreferences you should write following:

SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();

Variables PREFERNCES_FILE and PREFERENCES_LOGIN should be defined as String:

public static final String PREFERNCES_FILE = "my_preferences_file";
public static final String PREFERENCES_LOGIN = "login";

On logout there should be:

sp.edit().remove(PREFERENCES_LOGIN).apply();

Then to check if there is allready some info call:

boolean isLogged = sp.contains(PREFERENCES_LOGIN);

Then just set needed visibility:

login.setVisibility(isLogged ? View.GONE : View.VISIBLE);

UPDATE

Ok, here is example. This code should be in onCreate:

SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Button login = (Button)findViewById(R.id.btnLogin);
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
login.setOnClickListener(this);
Button logout = (Button)findViewById(R.id.btnLogout);
logout.setVisibility(isLogged ? View.VISIBLE : View.GONE);
logout.setOnClickListener(this);

And there should be button in your login_user xml with btnLogout id.
In onClick should be:

    @Override
    public void onClick(View v)
    {
        final int id = v.getId();
        switch (id) {
            case R.id.btnLogin:
                SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
                sp.edit().putString(PREFERENCES_LOGIN, login).apply();
                findViewById(R.id.btnLogin).setVisibility(View.GONE);
                findViewById(R.id.btnLogout).setVisibility(View.VISIBLE);
                //another actions after login
                break;
            case R.id.btnLogout:
                SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
                sp.edit().remove(PREFERENCES_LOGIN).apply();
                findViewById(R.id.btnLogin).setVisibility(View.VISIBLE);
                findViewById(R.id.btnLogout).setVisibility(View.GONE);
                //another actions after logout
                break;
            // even more buttons here
        }
    }

In login variable should be login data – I don’t know where you should get it.

4

solved How to use SharedPreferences to change view visibility in login and logout