【问题标题】:How can I fix this error that Showing NullException, but I already initialized the object of the button如何修复显示 NullException 的错误,但我已经初始化了按钮的对象
【发布时间】:2019-02-14 06:40:46
【问题描述】:

我遇到了这个错误,说 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 活动进行验证

【问题讨论】:

  • 您尚未为您的活动定义布局。 setContentView() 在哪里?
  • 你还记得,当你删除了setContentView()
  • 确保您的 id 指向布局中的正确项目。并确保您使用其他人提到的 setContentView()。没有 Pratik 有些人手动进行活动并将它们添加到他们的清单中忘记一些类似的事情。不是他们删除了它:)

标签: java android nullpointerexception


【解决方案1】:

关键线是这些。

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

错误消息说 NPE 被抛出是因为你在 null 上调用 setOnClickListener。这意味着btnVerifyOTPnull。这反过来意味着findViewById(R.id.btnVerifyOTP) 正在返回null

那为什么会这样呢?

一个可能的原因是您在调用setContentView 之前调用了findViewById;见findViewById returns null。事实上,正如其他人所指出的,你根本不打电话给setContentView

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


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

【讨论】:

    【解决方案2】:

    您忘记设置布局

    setContentView(R.layout.your_layout);
    

    【讨论】:

    • 应该是评论。
    • @PratikButani NO。只要它是正确的答案并解决 OP 的问题我的朋友。
    • 但这不是正确的答案。大约是正确答案的 1/4。
    • @StephenC 没有人会拒绝 1/4 的正确答案 * 眨眼眨眼 *
    • 我没有说 1/4 正确答案。我说的是正确答案的 1/4。正确的 1/4 是错误的。如果你暗示我对你投了反对票……你也错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2020-12-25
    • 2017-05-30
    相关资源
    最近更新 更多