实施SharedPreferences以保存用户数据?

时间:2017-01-12 18:56:08

标签: android sharedpreferences

我正在开发一个在Firebase中保存用户数据的应用程序,但每次重新启动应用程序时,用户必须再次登录,因为会话未保持打开状态,我已经读过我可以实现SharedPreferences但我不知道如何在我的项目中做到这一点。

这是LoginActivity.java:

public class LoginActivity extends AppCompatActivity {


private static final String TAG = "LoginActivity";
// La respuesta del JSON es
private static final String username = "success";
private static final String TAG_MESSAGE = "message";

private Button btnLogin, btnLinkToSignUp;
private ProgressBar progressBar;
private FirebaseAuth auth;
private EditText loginInputEmail, loginInputPassword;
private TextInputLayout loginInputLayoutEmail, loginInputLayoutPassword;


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

    loginInputLayoutEmail = (TextInputLayout) findViewById(R.id.login_input_layout_email);
    loginInputLayoutPassword = (TextInputLayout) findViewById(R.id.login_input_layout_password);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    loginInputEmail = (EditText) findViewById(R.id.login_input_email);
    loginInputPassword = (EditText) findViewById(R.id.login_input_password);

    btnLogin = (Button) findViewById(R.id.btn_login);
    btnLinkToSignUp = (Button) findViewById(R.id.btn_link_signup);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            submitForm();
        }
    });

    btnLinkToSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(appz.seoallinone.LoginActivity.this, SignupActivity.class);
            startActivity(intent);
        }
    });
}

/**
 * Validating form
 */
private void submitForm() {
    String email = loginInputEmail.getText().toString().trim();
    String password = loginInputPassword.getText().toString().trim();

    if(!checkEmail()) {
        return;
    }
    if(!checkPassword()) {
        return;
    }
    loginInputLayoutEmail.setErrorEnabled(false);
    loginInputLayoutPassword.setErrorEnabled(false);

    progressBar.setVisibility(View.VISIBLE);
    //authenticate user
    auth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // If sign in fails, Log a message to the LogCat. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    progressBar.setVisibility(View.GONE);
                    if (!task.isSuccessful()) {
                        // there was an error
                        Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();

                    } else {
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            });
}

private boolean checkEmail() {
    String email = loginInputEmail.getText().toString().trim();
    if (email.isEmpty() || !isEmailValid(email)) {

        loginInputLayoutEmail.setErrorEnabled(true);
        loginInputLayoutEmail.setError(getString(R.string.err_msg_email));
        loginInputEmail.setError(getString(R.string.err_msg_required));
        requestFocus(loginInputEmail);
        return false;
    }
    loginInputLayoutEmail.setErrorEnabled(false);
    return true;
}

private boolean checkPassword() {

    String password = loginInputPassword.getText().toString().trim();
    if (password.isEmpty() || !isPasswordValid(password)) {

        loginInputLayoutPassword.setError(getString(R.string.err_msg_password));
        loginInputPassword.setError(getString(R.string.err_msg_required));
        requestFocus(loginInputPassword);
        return false;
    }
    loginInputLayoutPassword.setErrorEnabled(false);
    return true;
}

private static boolean isEmailValid(String email) {
    return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

private static boolean isPasswordValid(String password){
    return (password.length() >= 6);
}

private void requestFocus(View view) {
    if (view.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

}

如何在这个特定项目中实现它?谢谢!

2 个答案:

答案 0 :(得分:1)

documentationStackOverflow可以轻松获得此答案。

要回答您的问题,您可以使用以下代码存储和获取首选项:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Car","Tesla");
editor.apply();


SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Car", "");

答案 1 :(得分:0)

FirebaseAuth已经负责为您保留Session。

您只需要检查用户是否存在于您的登录活动的onCreate中的Auth实例中:

if (FirebaseAuth.getInstance().getCurrentUser() != null) {
    navigateToHomeScreen();
}

您应该实施navigateToHomeScreen以启动活动以显示用户是否已登录。

这样,您无需在SharedPreferences中存储任何内容。