如何解决显示NullException的错误,但是我已经初始化了按钮的对象

时间:2019-02-14 06:40:47

标签: java android nullpointerexception

我陷入了说NullException的错误,但是我已经初始化了对象,但仍然显示null异常。 解决方法,我反复查看程序并设置断点,但没有结果

代码:

package com.rishavgmail.coder.carescountrysactionresourcesexigencyservices;

import android.arch.core.executor.TaskExecutor;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class VerifyPhone extends AppCompatActivity {
    private CoordinatorLayout coordinatorLayoutVerifyPhone;
    private TextInputLayout textInputLayoutOTP;
    private Button btnVerifyOTP;
    private String verificationID;
    private FirebaseAuth mAuth;
    private ProgressBar progressBarVerifyPhone;
    private String phoneNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAuth = FirebaseAuth.getInstance();
        String phoneNumber = getIntent().getStringExtra("phoneNumber");
        Initialization();
        sendVerificationCode(phoneNumber);
        btnVerifyOTP = findViewById(R.id.btnVerifyOTP);
        btnVerifyOTP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = textInputLayoutOTP.getEditText().getText().toString().trim();
                if (code.isEmpty())
                {
                    textInputLayoutOTP.setError("Enter OTP");
                    return;
                }
                else if (code.length()<6)
                {
                    textInputLayoutOTP.setError("Enter OTP");
                    return;
                }
                progressBarVerifyPhone.setVisibility(View.VISIBLE);
                verifyCode(code);
            }
        });
    }
    private void verifyCode(String code)
    {
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationID,code);
        ProceedToRegister(credential);
    }
    private void ProceedToRegister(PhoneAuthCredential credential)
    {
        mAuth.signInWithCredential(credential)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful())
                {
                    Intent intent=new Intent(VerifyPhone.this,AuthorityRegistration.class);
                    String AuthPhone = textInputLayoutOTP.getEditText().getText().toString().trim();
                    intent.putExtra("AuthPhone",AuthPhone);
                    startActivity(intent);
                }
                else
                {
                    Snackbar snackbar = Snackbar.make(coordinatorLayoutVerifyPhone,"Something went wrong !!",Snackbar.LENGTH_SHORT);
                    snackbar.show();
                }
            }
        });
    }
    private void Initialization()
    {
        progressBarVerifyPhone = findViewById(R.id.progressBarVerifyPhone);
        textInputLayoutOTP = findViewById(R.id.textInputLayoutVerifyOTP);
        coordinatorLayoutVerifyPhone = findViewById(R.id.coordinatorLayoutVerifyPhone);
    }
    private void sendVerificationCode(String number)
    {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(number,60,TimeUnit.SECONDS, TaskExecutors.MAIN_THREAD,mCallBack);
    }
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack =
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                    super.onCodeSent(s, forceResendingToken);

                    verificationID = s;
                }

                @Override
                public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

                    String code = phoneAuthCredential.getSmsCode();
                    if (code!=null)
                    {
                        progressBarVerifyPhone.setVisibility(View.VISIBLE);
                        verifyCode(code);
                    }
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                    Snackbar snackbar = Snackbar.make(coordinatorLayoutVerifyPhone,"Verification Failed !!",Snackbar.LENGTH_SHORT);
                    snackbar.show();
                }
            };
}

错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.rishavgmail.coder.carescountrysactionresourcesexigencyservices.VerifyPhone.onCreate(VerifyPhone.java:44)

它正在从Firebase发送OTP,但未启动VerifyOTP活动以进行验证

2 个答案:

答案 0 :(得分:0)

关键是这些。

btnVerifyOTP = findViewById(R.id.btnVerifyOTP);
btnVerifyOTP.setOnClickListener(new View.OnClickListener() { 
...

该错误消息表明,由于您正在setOnClickListener上调用null而引发了NPE。因此,这意味着btnVerifyOTPnull。这又意味着findViewById(R.id.btnVerifyOTP)返回null

那为什么会发生呢?

一个可能的原因是您在致电findViewById之前先致电setContentView

确实,正如其他人所指出的,您根本不打setContentView

假设这是问题所在,解决方法是在代码的前面添加一个setContentView调用;例如在您的Initialization方法被调用之前...,因为您也在此处使用findViewById


并且请更正方法名称中的样式错误。在Java中,方法名称应以小写字母开头。

答案 1 :(得分:-1)

您忘记设置布局

setContentView(R.layout.your_layout);