Firebase 9.0.0 mAuth.signInWithEmailAndPassword, how to pass it to a button

寵の児 提交于 2019-12-25 06:49:27

问题


Wonder why can't start the mAuth.signInWithEmailAndPassword() inside my onClick() button as I've done before. Should i call it another way? but how, It's not much of information out there yet about the new version.

Currently it gives be the error String is empty or null:

Process: com.example.rasmusjosefsson.rjcar, PID: 30563 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rasmusjosefsson.rjcar/com.example.rasmusjosefsson.rjcar.LoginAndSignUp.LoginActivity}: java.lang.IllegalArgumentException: Given String is empty or null at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.IllegalArgumentException: Given String is empty or null at com.google.android.gms.common.internal.zzaa.zzdl(Unknown Source) at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source) at com.example.rasmusjosefsson.rjcar.LoginAndSignUp.LoginActivity.onCreate(LoginActivity.java:77) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)

i guess it's because of the mAuth.signInWithEmailAndPassword(email, password) without any initiated String. and therefor will be called immediately inside onCreate().

public class LoginActivity extends AppCompatActivity {

    protected EditText emailEditText;
    protected EditText passwordEditText;
    protected Button loginButton;
    protected TextView signUpTextView;

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    // Currently 
    private String email;
    private String password;

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


        // Setting up the Views
        signUpTextView = (TextView) findViewById(R.id.signUpText);
        emailEditText = (EditText) findViewById(R.id.emailField);
        passwordEditText = (EditText) findViewById(R.id.passwordField);
        loginButton = (Button) findViewById(R.id.loginButton);


        // Getting the firebase reference url
        final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();


        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Retrieves user inputs
                email = emailEditText.getText().toString();
                password = passwordEditText.getText().toString();

                // trims the input
                email = email.trim();
                password = password.trim();


            }
        });


        // When a user signs in to your app, pass the user's email address and password to signInWithEmailAndPassword
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. 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.
                        if (!task.isSuccessful()) {
                            Log.w("TAG", "signInWithEmail", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });


        // responds to changes in the user's sign-in state
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());

                    // Authenticated successfully with authData
                    Intent intent = new Intent(LoginActivity.this, MainRealBack2.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                } else {
                    // User is signed out
                    Log.d("TAG", "onAuthStateChanged:signed_out");
                }
            }
        };


    }


    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

}

My activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainrealback2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        // User is signed in
        mUserId = user.getUid();


    } else {
        // No user is signed in
        loadLoginView();
    }

    waypointsUrl = Constants.FIREBASE_URL + "/users/" + mUserId + "/waypoints";
    mainRef = FirebaseDatabase.getInstance().getReferenceFromUrl(waypointsUrl);

UPDATE


回答1:


SOLUTION

To get .addOnCompleteListener() work inside setOnClickListener

.addOnCompleteListener() needed to be declared with classname.this

mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {

Final solution

public class LoginActivity extends AppCompatActivity {

protected EditText emailEditText;
protected EditText passwordEditText;
protected Button loginButton;
protected TextView signUpTextView;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

// Currently 
private String email;
private String password;

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


    // Setting up the Views
    signUpTextView = (TextView) findViewById(R.id.signUpText);
    emailEditText = (EditText) findViewById(R.id.emailField);
    passwordEditText = (EditText) findViewById(R.id.passwordField);
    loginButton = (Button) findViewById(R.id.loginButton);


    // Getting the firebase reference url
    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();


    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Retrieves user inputs
            email = emailEditText.getText().toString();
            password = passwordEditText.getText().toString();

            // trims the input
            email = email.trim();
            password = password.trim();


   // When a user signs in to your app, pass the user's email address and password to signInWithEmailAndPassword
    mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. 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.
                    if (!task.isSuccessful()) {
                        Log.w("TAG", "signInWithEmail", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });


        }
    });





    // responds to changes in the user's sign-in state
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());

                // Authenticated successfully with authData
                Intent intent = new Intent(LoginActivity.this, MainRealBack2.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);

            } else {
                // User is signed out
                Log.d("TAG", "onAuthStateChanged:signed_out");
            }
        }
    };


}


@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
 }

}



回答2:


You are calling mAuth.signInWithEmailAndPassword() inside onCreate() right away. You need to move it into your onClickListener.

 loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Retrieves user inputs
            email = emailEditText.getText().toString();
            password = passwordEditText.getText().toString();

            // trims the input
            email = email.trim();
            password = password.trim();

            mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. 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.
                    if (!task.isSuccessful()) {
                        Log.w("TAG", "signInWithEmail", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }
    });


来源:https://stackoverflow.com/questions/37352871/firebase-9-0-0-mauth-signinwithemailandpassword-how-to-pass-it-to-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!