首页 > 解决方案 > 在 firebase 数据库中搜索返回空值

问题描述

我正在开发一个应用程序,我必须从数据库中获取消息的状态,但是每当我尝试获取和显示数据时,应用程序都会崩溃回到主屏幕。

user = FirebaseAuth.getInstance().getCurrentUser();
   String uid = user.getUid();
   database = FirebaseDatabase.getInstance();
   String msg = textView.getText().toString().trim();
   DatabaseReference myRef = database.getReference();
   myRef.child("Users").child(uid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
           for(DataSnapshot db : dataSnapshot.getChildren()) {
              if(db.getKey().equals(textView.getText().toString().trim())) {
                  count=1;
                  String key = db.getKey();
                  String key2= db.child(key).child("status").getValue(String.class);
                                Toast.makeText(CheckMsg.this,key2, Toast.LENGTH_SHORT).show();
           }
        }
   }

数据库格式

这就是我的数据库格式的样子

标签: androidfirebasefirebase-realtime-database

解决方案


I am assuming the crash is because key2 is null:

In the for loop:

Change this:

String key2= db.child(key).child("status").getValue(String.class);

to this:

String key2= db.child("status").getValue(String.class);

推荐阅读