Usman
Usman

Reputation: 84

Searching in firebase database returns null value

I am working on an app where I have to fetch the status of a message from the database, but whenever I try to fetch and display data, the app crashes back to home screen.

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();
           }
        }
   }

Database Format

This is how my database format looks

Upvotes: 2

Views: 206

Answers (3)

Hasan Bou Taam
Hasan Bou Taam

Reputation: 4035

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);

Upvotes: 1

DikShU
DikShU

Reputation: 96

After Reading your Details Provided.

Issues- 1) Update the key as
String key2=db.child("status").getValue(String.class);

Try this. If this doesn't Work, comment below...

Upvotes: 0

Chaitanya Chavali
Chaitanya Chavali

Reputation: 853

You should modify the key2 statement to

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

OR

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

db is already a child as it is an element of getChildren()(like abc and all) and you are trying to find a child of abc with the name abc.

Upvotes: 1

Related Questions