Firebase身份验证android.view.View $ OnClickListener错误消息

时间:2019-09-26 17:55:13

标签: android firebase firebase-authentication

我正在尝试使用Firebase对用户进行身份验证。我尝试使用Firebase quick start sample,只是将其更改为我已经创建的内容,但我不断出错。我已经看到了一些关于SO的示例和问题解决方案,它们帮助我解决了几个问题,但我仍然陷于困境。我得到的最新错误是:

Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/System: ClassLoader referenced unknown path: /data/app/com.example.myproject-2/lib/arm
V/FA: Registered activity lifecycle callback
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
I/FirebaseInitProvider: FirebaseApp initialization successful
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
    Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
V/FA: Collection enabled
    App package, google app id: com.example.myproject, 1:1068609878538:android:9b5be5dc4e43735d9f7df3
I/FA: App measurement is starting up, version: 18202
    To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
    To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.example.myproject
D/FA: Debug-level message logging enabled
V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
    mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
    mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
    mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
    mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@4a7b963
    BoostFramework() : mPerf = com.qualcomm.qti.Performance@b784960
V/FA: Connecting to remote service
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@98e1aea
D/MainActivity: onCreate: starting.
D/MainActivity: setupBottomNavigationView: setting up bottom navigation view
D/BottomNavigationViewHel: setupBottomNavigationView: Setting up bottom navigation view.
D/MainActivity: onStart: Starting MainActivity onStart method.
    updateUI: checking if user is logged in.
D/MainActivity: onStart:signed_out. 
V/FA: Activity resumed, time: 6079852
I/FA: Tag Manager is not found and thus will not be used
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/FA: Logging event (FE): screen_view(_vs), Bundle[{ga_event_origin(_o)=auto, ga_screen_class(_sc)=MainActivity, ga_screen_id(_si)=-2493293364558908427}]
V/FA: Connection attempt already in progress
    Connection attempt already in progress
    Screen exposed for less than 1000 ms. Event not sent. time: 77
V/FA: Connection attempt already in progress
    Activity paused, time: 6079882
D/EmailPassword: onCreate: started.
V/FA: onActivityCreated
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myproject, PID: 23204
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myproject/com.example.myproject.Login.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)

这是我的代码:

public class LoginActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "EmailPassword";

    private TextView mStatusTextView;
    private TextView mDetailTextView;
    private EditText mEmailField;
    private EditText mPasswordField;

    private FirebaseAuth mAuth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: started.");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Views
        mEmailField = findViewById(R.id.input_email);
        mPasswordField = findViewById(R.id.input_password);

        // Buttons
        findViewById(R.id.btn_login).setOnClickListener((View.OnClickListener) this);
        findViewById(R.id.btn_register).setOnClickListener((View.OnClickListener) this);

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        signOut();

    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart: started.");
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }

    private void createAccount(String email, String password) {
        Log.d(TAG, "createAccount:" + email);
        if (!validateForm()) {
            return;
        }

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(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, "createUserWithEmail:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                    }
                });

    }

    private void signIn(String email, String password) {
        Log.d(TAG, "signIn:" + email);
        if (!validateForm()) {
            return;
        }

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(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();
                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                        if (!task.isSuccessful()) {
                            mStatusTextView.setText(R.string.auth_failed);
                        }
                    }
                });
    }

    private void signOut() {
        Log.d(TAG, "signOut: started.");
        mAuth.signOut();
        updateUI(null);
    }

    private boolean validateForm() {
        Log.d(TAG, "validateForm: started.");
        boolean valid = true;

        String email = mEmailField.getText().toString();
        if (TextUtils.isEmpty(email)) {
            mEmailField.setError("Required.");
            valid = false;
        } else {
            mEmailField.setError(null);
        }

        String password = mPasswordField.getText().toString();
        if (TextUtils.isEmpty(password)) {
            mPasswordField.setError("Required.");
            valid = false;
        } else {
            mPasswordField.setError(null);
        }
        return valid;
    }

    private void updateUI(FirebaseUser user) {
        Log.d(TAG, "updateUI: started.");
        if (user != null) {
            mStatusTextView.setText(getString(R.string.emailpassword_status_fmt, user.getEmail(), user.isEmailVerified()));
            mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
        } else {
            findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
            findViewById(R.id.pleaseWait).setVisibility(View.GONE);
            findViewById(R.id.progressBar).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        Log.d(TAG, "onClick: started.");
        findViewById(R.id.btn_login).setOnClickListener((View.OnClickListener) this);
        findViewById(R.id.btn_register).setOnClickListener((View.OnClickListener) this);

        int i = view.getId();
        if (i == R.id.btn_register) {
        createAccount(mEmailField.getText().toString(), mPasswordField.getText().toString());
        } else if (i == R.id.btn_login) {
        signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

1。)确保调用findViewById()时使用的ID实际上存在。

2。)声明一个合适的变量来存储视图,我假设您正在使用Button,所以:

Button loginBtn;

public void onCreate(Bundle savedInstanceState) { 
    .......
    loginBtn = findViewById(R.id.btn_login);
    .......
}

3。)现在,您可以实现OnClickListener或简单地将其附加为:

loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do your stuff
            }
        }); 

或通过实现OnClickListener:

@Override
public void onClick(View view) {
    Log.d(TAG, "onClick: started.");
    //Remove the extra call to attach the listener

    int i = view.getId();
    if (i == R.id.btn_register) {
    createAccount(mEmailField.getText().toString(), mPasswordField.getText().toString());
    } else if (i == R.id.btn_login) {
    signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
    }
}

确保您删除了onClick()

中多余的侦听器附件调用