Home > Blockchain >  Error Using SharedPreferences() Method In Android Studio (Login Activity) After Adding Firebase Auth
Error Using SharedPreferences() Method In Android Studio (Login Activity) After Adding Firebase Auth

Time:01-03

My code worked until I added Firebase to it. This is my login page, and the SharedPreferences don't work. When I click on the login button, the password pops up as the username and the password - and then when I re-run the emulator - the username and the password are null. Please help me find the error:


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class Login extends AppCompatActivity {
    EditText username;
    EditText etPassword;
    Button loginBtn;
    Button registerBtn;
    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    private static String TAG = "Michael's Tracking --> ";
    private FirebaseAuth mAuth;

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

        Log.d(TAG, "Start onCreate");

        username = findViewById(R.id.username);
        etPassword = findViewById(R.id.etPassword);
        loginBtn = findViewById(R.id.registerBtn);
        registerBtn = findViewById(R.id.toLoginBtn);

        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mEditor = mPreferences.edit();

        mAuth = FirebaseAuth.getInstance();

            super.onStart();
            // Check if user is signed in (non-null) and update UI accordingly.
            FirebaseUser currentUser = mAuth.getCurrentUser();
            if(currentUser != null){
                currentUser.reload();
            }

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String email = username.getText().toString();
                String pass = etPassword.getText().toString();

                String stName = email;
                mEditor.putString(getString(R.string.name), stName);
                mEditor.commit();

                String stPassword = pass;
                mEditor.putString(getString(R.string.password), stPassword);
                mEditor.commit();

                checkSharedPreferences();

                mAuth.signInWithEmailAndPassword(email, pass)
                        .addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    // Sign in success, update UI with the signed-in user's information
                                    Log.d(TAG, "signInWithEmail:success");
                                    FirebaseUser user = mAuth.getCurrentUser();
                                    startActivity(new Intent(Login.this, MainPage.class));
                                } else {
                                    // If sign in fails, display a message to the user.
                                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                                    Toast.makeText(Login.this, "Authentication failed.",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        });

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent registerPage = new Intent(Login.this, Register.class);
                startActivity(registerPage);

            }
        });
    }

    private void checkSharedPreferences() {
        String stName, stPassword;
        stName = mPreferences.getString(getString(R.string.name), "");
        stPassword = mPreferences.getString(getString(R.string.password), "");
        username.setText(stName);
        etPassword.setText(stPassword);
    }

}```

Thank you very much!

CodePudding user response:

checkSharedPreferences() method shouldn't be called inside onClick, it's for restoring data, so it should be called at the beginning, so in onCreate after taking references to Views (findViewById) and preferences (mPreferences, mEditor)

CodePudding user response:

Use shared preference to store username and password after successful login.

      mAuth.signInWithEmailAndPassword(email, pass)
                        .addOnCompleteListener(Login.this, new
                                OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        if (task.isSuccessful()) {
                                            // Sign in success, update UI with the signed-in user's information
                                            Log.d(TAG, "signInWithEmail:success");
                                            FirebaseUser user = mAuth.getCurrentUser();
                                            mEditor.putString("Useranme", stName);

                                            mEditor.putString("Password", stPassword);
                                                    mEditor.commit();
                                            startActivity(new Intent(Login.this, MainPage.class));
                                        } else {
                                            // If sign in fails, display a message to the user.
                                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                                            Toast.makeText(Login.this, "Authentication failed.",
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
            }
        });         
  • Related