0

I am developing an application that saves user data in Firebase, but every time the app is restarted the user must log in again because the session is not kept open, I have read that I can implement SharedPreferences but I do not know how to do it in my project.

Here is the 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);
}

}

How can I implement it in this specific project?. Thank you!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • [The Android documentation](https://developer.android.com/training/basics/data-storage/shared-preferences.html) is a good start. For something more straight to the point you can check [this link](http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126) – maxoumime Jan 12 '17 at 19:00

2 Answers2

1

This answer is easily available in both the documentation and StackOverflow.

To answer your question, you can use the following code to store and fetch preferences:

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", "");
Community
  • 1
  • 1
Orbit
  • 2,985
  • 9
  • 49
  • 106
0

The FirebaseAuth already takes care of keeping the Session for you.

You just need to check if the user exists in the Auth instance in the onCreate of your login activity:

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

You should implement navigateToHomeScreen to start the activity to show if the user is logged in.

This way, you don't need to store anything in the SharedPreferences.

BMacedo
  • 768
  • 4
  • 10