Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

SharedPreferences

/*============StartActivity.java============*/

public class StartActivity extends AppCompatActivity {

private static final String PREF_LOGIN = "LOGIN_PREF";
private static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences preferences = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE);

    Intent intent = null;
    if(preferences.contains(KEY_CREDENTIALS)){              //if user is currently logged in;
        intent = new Intent(this, MainActivity.class);
    }else {                                                 //if user is not yet logged in;
        intent = new Intent(this, LoginActivity.class);
    }
    startActivity(intent);
}

}

/*============LoginActivity.java============*/

public class LoginActivity extends AppCompatActivity {

public static final String PREF_LOGIN = "LOGIN_PREF";
public static final String KEY_CREDENTIALS = "LOGIN_CREDENTIALS";

private Button loginButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //...

    loginButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //call login api...


            //on your sucess callback; we save the credentials...
            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.putString(KEY_CREDENTIALS, "DUMMY CREDENTIALS");
            editor.commit();
            */

            //on your failure callback; we clear the credentials...

            /*
            SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
            */
        }


    });
}
 
PREVIOUS NEXT
Tagged: #SharedPreferences
ADD COMMENT
Topic
Name
9+7 =