0

I got stuck in this error saying NullException but I initialized my objects already but it still showing null exception. How to solve it, I review the program again and again and set breakpoints too but no results

Code :

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();
                }
            };
}

Error :

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)

It's sending the OTP from the Firebase but not starting the VerifyOTP activity for verification

V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
Hacker X
  • 24
  • 6
  • you haven't defined layout for your activity. Where is `setContentView()` ? – Vivek Mishra Feb 14 '19 at 06:44
  • Do you remember, when you have removed `setContentView()` – Pratik Butani Feb 14 '19 at 06:53
  • Make sure your id is pointing to the right item in your layout.And make sure you use setContentView() as mentioned by others.No Pratik some people make their activities manually and add them to the manifest they forget a few things like that.It's not that they removed it :) – Steve Moretz Feb 14 '19 at 06:55

2 Answers2

1

The key lines are these one.

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

The error message says that the NPE being thrown because you are calling setOnClickListener on null. So that means btnVerifyOTP is null. And that in turn means that findViewById(R.id.btnVerifyOTP) is returning null.

So why would that happen?

Well one possible reason is that you have called findViewById before calling setContentView; see findViewById returns null. Indeed, as others have pointed out, you don't call setContentView at all.

Assuming that this is the problem, the fix is to put an add a setContentView call earlier in the code; e.g. before your Initialization method is called ... because you are using findViewById there too!


And please correct the style errors in your method names. In Java method name should start with a lower case letter.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1

You forgot to set your layout

setContentView(R.layout.your_layout);
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50