【问题标题】:My 'MainActivity' keeps crashing. I don't know if it's my code, database setup or something else我的“MainActivity”不断崩溃。我不知道是我的代码、数据库设置还是其他原因
【发布时间】:2021-03-10 15:13:48
【问题描述】:

我在使用教程要求的新更改时遇到问题。我完全遵循了编码规则(新版本中的新“快照”条目除外),但我的“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();
            }
        }

Logcat

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 上查找,并将其添加到您的问题中。
  • 嗨@AlexMamo。我添加了 Logcat。如果您可以检测到我的代码或数据库的问题,请告诉我。再次感谢您的帮助
  • 告诉我们usersDb是如何实例化的?
  • 嗨@AlexMamo 我已经编辑了问题以深入展示usersDb。请让我知道您还需要看什么。再次感谢
  • 您的usersDb 对象是否在使用的同一类中定义?

标签: android firebase firebase-realtime-database tinder


【解决方案1】:

我知道我哪里出错了,那是我的编码结构。 logcat 中出现了两个错误:checkUserSex();'声明(第 48 行)和数据库引用(第 141 行)。这只是放置我的“checkUserSex();”的情况。在我的“onCreate”的其他声明下方(因此在 usersDb、mAuth 和 currentUId 下方。

【讨论】:

    【解决方案2】:

    由于user.getUid() 返回 NULL,您将收到 Null 指针异常。因此,每当user.getUid() 为NULL 时,您的应用程序必须提示用户登录。登录成功后,您的应用程序必须遵循您的常规工作流程,例如checkUserSex()

    以下解决方案可能会对您有所帮助(示例代码显示 Firebase Google 身份验证)

    在您的活动中声明以下附加变量

    private static final int RC_SIGN_IN = 1;
    private FirebaseAuth mAuth;
    private GoogleSignInClient mGoogleSignInClient;
    

    修改你的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, "login failed", 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'
    

    在您的 Firebase 控制台中启用 Google 身份验证

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2015-07-24
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      相关资源
      最近更新 更多