0

I have used phone authentication in my app. While authenticating with phone number which is in same mobile it fails and show error for null pointer exception of Realtime database, but while authenticating with phone number which is in another phone and app in another phone it works perfectly. Why it fails for phone number in same mobile containing app?

Otpverify.kt

package com.bookqueen.bookqueen.Activity

class OtpVerfiy : AppCompatActivity() {

lateinit var auth: FirebaseAuth
lateinit var storedVerificationId: String
lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
lateinit var verify: Button
lateinit var resendotp: TextView
lateinit var numbertext: TextView
lateinit var progressBar: ProgressBar
lateinit var database: FirebaseDatabase
lateinit var databaseReference: DatabaseReference
lateinit var number: String
lateinit var otp: EditText


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_otp_verfiy)
    auth = FirebaseAuth.getInstance()
    verify = findViewById(R.id.btnverify)
    resendotp = findViewById(R.id.resendotp)
    progressBar = findViewById(R.id.progressBar)
    numbertext = findViewById(R.id.intnumber)
    otp = findViewById(R.id.edtotp)
    progressBar.visibility = View.GONE
    database = FirebaseDatabase.getInstance()
    databaseReference = database.getReference("Users")

    val mobileNumber = intent.getStringExtra("mobilenumber")
    number = "+91" + mobileNumber.toString().trim()
    numbertext.text = number


    verify.setOnClickListener {
        //val otp = findViewById<EditText>(R.id.edtotp).text.toString().trim()
        if (TextUtils.isEmpty(otp.text.toString())) {
            otp.error = getString(R.string.enterotp)
        } else if (otp.length() > 0 || otp.length() == 4) {
            progressBar.visibility = View.VISIBLE
            val credential: PhoneAuthCredential = PhoneAuthProvider.getCredential(
                storedVerificationId.toString(), otp.text.toString().trim()
            )
            signInWithPhoneAuthCredential(credential)
        } else {
            Toast.makeText(this, getString(R.string.invalidotp), Toast.LENGTH_SHORT).show()
            progressBar.visibility = View.GONE
        }
    }
    resendotp.setOnClickListener {

        resendcodeforverification(number, resendToken)
        Toast.makeText(this, getString(R.string.otpsent), Toast.LENGTH_SHORT).show()
    }

    callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        override fun onVerificationCompleted(credential: PhoneAuthCredential) {
            startActivity(Intent(applicationContext, MainActivity::class.java))
            finish()
        }

        override fun onVerificationFailed(e: FirebaseException) {
             Toast.makeText(applicationContext, getString(R.string.verificationfailed), 
Toast.LENGTH_LONG).show()
        }

        override fun onCodeSent(
            verificationId: String,
            token: PhoneAuthProvider.ForceResendingToken
        ) {
            storedVerificationId = verificationId
            resendToken = token

        }
    }

    sendVerificationcode(number)

}

private fun sendVerificationcode(number: String) {
    val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(number)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(this)
        .setCallbacks(callbacks)
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
}

private fun resendcodeforverification(
    phone: String,
    token: PhoneAuthProvider.ForceResendingToken?
) {


    val option = PhoneAuthOptions.newBuilder()
        .setPhoneNumber(phone)
        .setTimeout(60L, TimeUnit.SECONDS)
        .setActivity(this)
        .setCallbacks(callbacks)
        .setForceResendingToken(token!!)
        .build()
    PhoneAuthProvider.verifyPhoneNumber(option)


}

private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                Toast.makeText(this, getString(R.string.signinsuccess), 
Toast.LENGTH_SHORT).show()
                databaseReference.orderByChild("Phone").equalTo(number)
                    .addListenerForSingleValueEvent(object : ValueEventListener {
                        override fun onDataChange(snapshot: DataSnapshot) {
                            if (snapshot.value != null) {
                                startActivity(
                                    Intent(
                                        applicationContext,
                                        MainActivity::class.java
                                    )
                                )
                                progressBar.visibility = View.GONE
                                finish()
                            } else {

                                startActivity(
                                    Intent(
                                        applicationContext,
                                        SaveProfile::class.java
                                    )
                                )
                                progressBar.visibility = View.GONE
                                finish()
                            }
                        }

                        override fun onCancelled(error: DatabaseError) {
                            Toast.makeText(this@OtpVerfiy, error.message, Toast.LENGTH_SHORT)
                                .show()
                        }

                    })

            } else {
                if (task.exception is FirebaseAuthInvalidCredentialsException) {
                    Toast.makeText(this, getString(R.string.invalidotp), 
Toast.LENGTH_SHORT).show()
                    progressBar.visibility = View.GONE
                }
            }
        }
        .addOnFailureListener { e ->
            Toast.makeText(this, e.message.toString(), Toast.LENGTH_SHORT).show()
            progressBar.visibility = View.GONE

        }
}

}

Error Message

2021-11-19 08:58:35.920 26039-26039/com.bookqueen.bookqueen 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bookqueen.bookqueen, PID: 26039
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.bookqueen.bookqueen/com.bookqueen.bookqueen
.Activity.MainActivity}: java.lang.NullPointerException at 
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:3534) at 
android.app.ActivityThread.handleLaunchActivity
(ActivityThread.java:3689)at 
android.app.servertransaction.LaunchActivityItem.execute
(LaunchActivityItem.java:83) at 
android.app.servertransaction.TransactionExecutor.executeCallbacks
(TransactionExecutor.java:140)at 
android.app.servertransaction.TransactionExecutor.execute
(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2239)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:227)
    at android.app.ActivityThread.main(ActivityThread.java:7822)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
   (RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)
 Caused by: java.lang.NullPointerException at
 com.bookqueen.bookqueen.Activity.MainActivity
.onCreate(MainActivity.kt:40)
    at android.app.Activity.performCreate(Activity.java:7969)
    at android.app.Activity.performCreate(Activity.java:7958)
    at android.app.Instrumentation.callActivityOnCreate
    (Instrumentation.java:1306)
    at android.app.ActivityThread.performLaunchActivity
    (ActivityThread.java:3505)

build.gradle(:app)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId "com.bookqueen.bookqueen"
    minSdkVersion 18
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android- 
optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-analytics-ktx:19.0.0'
implementation 'com.google.firebase:firebase-database-ktx:20.0.1'
implementation 'com.google.firebase:firebase-firestore-ktx:23.0.3'
implementation 'com.google.firebase:firebase-storage-ktx:20.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

//material design

implementation 'com.google.android.material:material:1.5.0-alpha01'
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:28.3.0')

// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don't specify versions in Firebase library 
dependencies
implementation 'com.google.firebase:firebase-auth-ktx'

implementation 'com.google.android.material:material:1.1.0'

implementation 'com.squareup.picasso:picasso:2.71828'

implementation 'com.google.android.material:material:1.3.0-alpha03'

implementation 'de.hdodenhof:circleimageview:3.1.0'

implementation 'com.github.smarteist:autoimageslider:1.4.0'

implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")


}
Ashish Dawkhar
  • 131
  • 1
  • 9
  • "show error for null pointer exception" Please edit your question to the exact error message and its complete stack trace. – Frank van Puffelen Nov 18 '21 at 14:52
  • Sir, I have edited the question and added error message it occurs only when trying to authenticate using phone number in same mobile containing app and works perfectly with phone number in different mobile and app in different mobile. – Ashish Dawkhar Nov 19 '21 at 03:42
  • That shows a `java.lang.NullPointerException`, so you might want to have a look at https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it to see how to troubleshoot that. – Frank van Puffelen Nov 19 '21 at 04:12
  • But it works fine with phone number which is in different phone and exception occurred in mainactivity and authentication is in another activity so why it happens. – Ashish Dawkhar Nov 19 '21 at 04:57

0 Answers0