我无法在android studio中将PhoneAuthOptions与Firebase一起使用

yftpprvb  于 2023-03-24  发布在  Android
关注(0)|答案(1)|浏览(178)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileOptions {
    sourceCompatibility 1.8
    targetCompatibility 1.8
}

compileSdkVersion 32
buildToolsVersion "33.0.2"

defaultConfig {
    multiDexEnabled true
    applicationId "com.pratapbrothers.jnvsocialconnection"
    minSdkVersion 19
    targetSdkVersion 32
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

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

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation 'com.github.yalantis:ucrop:2.2.6'
    implementation 'io.github.chaosleung:pinview:1.4.4'

    // Firebase
    implementation platform('com.google.firebase:firebase-bom:31.2.3')
    implementation 'com.google.firebase:firebase-auth-ktx'
    implementation 'com.google.firebase:firebase-database-ktx'
    implementation 'com.google.firebase:firebase-storage-ktx'
}

下面是我用来导入数据库的代码

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

private FirebaseAuth firebaseAuth;
private DatabaseReference userDatabaseRef;
private StorageReference userProfileImageRef;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_details);

    getSupportActionBar().setTitle("Set up you account");

    initialize();

    customProgressDialog = new CustomProgressDialog(this);

    firebaseAuth = FirebaseAuth.getInstance();
    currentUserId = firebaseAuth.getCurrentUser().getUid();
    userProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile images");
    userDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);

    )
)

同样的错误也出现在

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

---------碰撞开始

2023-03-22 14:19:07.621 3181-3181/com.pratapbrothers.jnvsocialconnection E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pratapbrothers.jnvsocialconnection, PID: 3181
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pratapbrothers.jnvsocialconnection/com.pratapbrothers.jnvsocialconnection.OtpActivity}: java.lang.NullPointerException: null reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3735)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3903)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2328)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:255)
    at android.app.ActivityThread.main(ActivityThread.java:8212)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
 Caused by: java.lang.NullPointerException: null reference
    at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source:2)
    at com.google.firebase.auth.PhoneAuthOptions$Builder.<init>(com.google.firebase:firebase-auth@@19.3.2:2)
    at com.google.firebase.auth.PhoneAuthOptions.newBuilder(com.google.firebase:firebase-auth@@19.3.2:27)
    at com.pratapbrothers.jnvsocialconnection.OtpActivity.sendVerificationCode(OtpActivity.java:79)
    at com.pratapbrothers.jnvsocialconnection.OtpActivity.onCreate(OtpActivity.java:55)
    at android.app.Activity.performCreate(Activity.java:8151)
    at android.app.Activity.performCreate(Activity.java:8135)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3704)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3903) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2328) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:255) 
    at android.app.ActivityThread.main(ActivityThread.java:8212) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049) 
    2023-03-22 14:19:07.638 3181-3181/com.pratapbrothers.jnvsocialconnection         I/Process: Sending signal. PID: 3181 SIG: 9

这里是OtpActivity.java

package com.pratapbrothers.jnvsocialconnection;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.chaos.view.PinView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class OtpActivity extends AppCompatActivity {
private TextView textSub, textError;
private PinView pinView;
private Button verifyButton;

private String phoneNumber, verificationId;

private CustomProgressDialog customProgressDialog;

private FirebaseAuth firebaseAuth;
private PhoneAuthOptions phoneAuthOptions;

private void initialize() {
    textSub = findViewById(R.id.textSub);
    textError = findViewById(R.id.textError);
    pinView = findViewById(R.id.pinView);
    verifyButton = findViewById(R.id.verifyButton);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp);

    initialize();

    phoneNumber = getIntent().getStringExtra("phone_number");

    sendVerificationCode(phoneNumber);

    customProgressDialog = new CustomProgressDialog(this);

    textError.setVisibility(View.INVISIBLE);

    pinView.requestFocus();

    getSupportActionBar().setTitle("Verify your phone number");

    textSub.setText("Enter the 6-digit OTP sent to your phone number " + phoneNumber + " to verify");

    verifyButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            verifyCode(pinView.getText().toString());
        }
    });

}

private void sendVerificationCode(String number) {
    PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
                    .setPhoneNumber(number)
                    .setTimeout(60L, TimeUnit.SECONDS)
                    .setActivity(this)
                    .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

                        @Override
                        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                            verificationId = s;
                            Toast.makeText(OtpActivity.this, "OTP sent", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {

                            final String code = phoneAuthCredential.getSmsCode();

                            if (code != null) {
                                pinView.setText(code);
                                verifyCode(code);
                            }
                        }

                        @Override
                        public void onVerificationFailed(@NonNull FirebaseException e) {

                        }
                    })
                    .build();

    PhoneAuthProvider.verifyPhoneNumber(options);
}

private void verifyCode(String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithCredential(credential);
}

private void signInWithCredential(PhoneAuthCredential credential) {
    firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Intent i = new Intent(OtpActivity.this, MainActivity.class);
                        startActivity(i);
                        finish();

                    } else {
                        Toast.makeText(OtpActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            });
    }
}

以下是我的问题

其实我做一个应用程序,如社会媒体,在这里我使用电话号码登录选项,让我的用户登录电话号码和存储他们的数据,如姓名,出生日期,性别,工作等数据库。
在初始化时一切都很好,甚至数据库也工作一切都正常,但当我在那里实现电话号码登录方法时,它需要一个名为PhoneAuthOptions的类,而这个类在firebase库中不可用。我在互联网上搜索错误,发现我应该使用firebase bom,当我使用这个时,它就这样做了,但它也犯了数据库错误。
我必须使用这两个库(电话号码登录,数据库)在我的应用程序

oalqel3c

oalqel3c1#

PhoneAuthOptions类存在于com.google.firebase.auth包中。因此,如果你想在Android应用中使用该依赖项,我建议你使用以下代码行:

implementation platform("com.google.firebase:firebase-bom:31.2.3")
implementation "com.google.firebase:firebase-auth-ktx"

对于其他Firebase服务,请添加以下依赖项:

implementation "com.google.firebase:firebase-database-ktx"
implementation "com.google.firebase:firebase-storage-ktx"

如果使用BOM,就不需要再指定版本了,如果使用Java,可以省略上面行中的-ktx

相关问题