问题描述
我在使用教程要求的新更改来运行我的应用程序时遇到问题。我完全遵循了编码规则(新版本的新“快照”条目除外),但我的“MainActivity”一直崩溃。用户仍在身份验证中注册,但数据库并没有像我希望的那样注册他们。
错误控制台指向'DatabaseReference userDb = usersDb.child(user.getUid());'作为崩溃的原因。我认为数据库可能有问题,因为尚不完全清楚如何设置它。如果有新的编码建议可以解决这个问题,或者我是否遗漏了数据库设置中的某些内容,请告诉我。请帮忙。
这里也是我正在关注的教程的链接:https://www.youtube.com/watch?v=RagA8g9A5Qc&list=PLxabZQCAe5fio9dm1Vd0peIY6HLfo5MCf&index=17
private String userSex;
private String notUserSex;
public void checkUserSex() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference userDb = usersDb.child(user.getUid());
userDb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
if (snapshot.child("sex").getValue() != null) {
userSex = snapshot.child("sex").getValue().toString();
switch (userSex) {
case "Male":
notUserSex = "Female";
break;
case "Female":
notUserSex = "Male";
break;
}
getoppositeSexUsers();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
public void getoppositeSexUsers(){
usersDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot,@Nullable String prevIoUsChildName) {
if (snapshot.exists() && !snapshot.child("connections").child("no").hasChild(currentUId) && !snapshot.child("connections").child("yes").hasChild(currentUId) && snapshot.child("sex").getValue().toString().equals(notUserSex)){
String profileImageUrl = "default";
if(snapshot.child("profileImageUrl").getValue()!=null) {
if (!snapshot.child("profileImageUrl").getValue().equals("default")) {
profileImageUrl = snapshot.child("profileImageUrl").getValue().toString();
}
}
cards item = new cards(snapshot.getKey(),snapshot.child("name").getValue().toString(),profileImageUrl);
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
日志猫
2021-03-10 15:48:00.372 9915-9915/com.bendes.tinder2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bendes.tinder2,PID: 9915
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bendes.tinder2/com.bendes.tinder2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at com.bendes.tinder2.MainActivity.checkUserSex(MainActivity.java:141)
at com.bendes.tinder2.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-03-10 15:48:00.438 9915-9915/com.bendes.tinder2 I/Process:发送信号。 PID:9915 SIG:9
public class MainActivity extends AppCompatActivity {
private cards cards_data[];
private arrayAdapter arrayAdapter;
private int i;
private Button logout;
private FirebaseAuth mAuth;
private String currentUId;
private DatabaseReference usersDb;
ListView listView;
List<cards> rowItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkUserSex();
usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUId = mAuth.getCurrentUser().getUid();
logout = (Button) findViewById(R.id.signout);
logout.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(MainActivity.this,ChooseLoginorRegistrationActivity.class));
}
});
解决方法
我知道我哪里出错了,这是我的编码结构。 logcat 中出现两个错误: checkUserSex();'声明(第 48 行)和数据库引用(第 141 行)。这只是放置我的“checkUserSex();”的一个例子在我的“onCreate”的其他声明之下(所以在 usersDb、mAuth 和 currentUId 之下。
,您收到空指针异常,因为 user.getUid()
返回 NULL。因此,只要 checkUserSex()
为 NULL,您的应用程序必须提示用户登录。登录成功后,您的应用程序必须遵循您的常规工作流程,例如private static final int RC_SIGN_IN = 1;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
以下解决方案可能对您有所帮助(示例代码显示 Firebase Google 身份验证)
在您的活动中声明以下附加变量
onCreate()
如下修改您的 @Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main2 );
GoogleSignInOptions gso = new GoogleSignInOptions.Builder ( GoogleSignInOptions.DEFAULT_SIGN_IN )
.requestIdToken ( getString ( R.string.default_web_client_id ) )
.requestEmail ()
.build ();
mGoogleSignInClient = GoogleSignIn.getClient ( this,gso );
mAuth = FirebaseAuth.getInstance();
checkFirebaseUser ( mAuth.getCurrentUser () );
}
方法
private void checkFirebaseUser ( FirebaseUser currentUser ) {
if (currentUser != null) {
//Continue with your regular flow
checkUserSex ();
} else {
//Sign In flow
Intent signInIntent = mGoogleSignInClient.getSignInIntent ();
startActivityForResult ( signInIntent,RC_SIGN_IN );
}
}
@Override
public void onActivityResult ( int requestCode,int resultCode,Intent data ) {
super.onActivityResult ( requestCode,resultCode,data );
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent ( data );
try {
GoogleSignInAccount account = task.getResult ( ApiException.class );
assert account != null;
firebaseAuthWithGoogle ( account.getIdToken () );
} catch (Exception e) {
Toast.makeText ( this,"login failed",Toast.LENGTH_SHORT ).show ();
}
}
}
private void firebaseAuthWithGoogle ( String idToken ) {
AuthCredential credential = GoogleAuthProvider.getCredential ( idToken,null );
mAuth.signInWithCredential ( credential )
.addOnCompleteListener ( this,task -> {
if (task.isSuccessful ()) {
Toast.makeText ( this,"login success",Toast.LENGTH_SHORT ).show ();
FirebaseUser user = mAuth.getCurrentUser ();
checkFirebaseUser ( user );
} else {
Toast.makeText ( this,Toast.LENGTH_SHORT ).show ();
}
} );
}
将以下附加方法添加到您的活动中(用于身份验证)
build.gradle
确保在 implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation 'com.google.firebase:firebase-auth:20.0.3'
中添加以下依赖项以进行身份验证
lang
在 Firebase 控制台中启用 Google 身份验证