Ashi
Ashi

Reputation: 13

How to retrieve a specific data from a node in Firebase Realtime Database using Android Studio?

How can I retrieve data from a specific node ID in Firebase using Android Studio where I have an activity to enter the ID in EditText? Also I have a button which when pressed should display the data under that ID.

Firebase DB Format:(As I cant upload image)
--> CEVM
     --Random
       --bKIG89-BX78BkuO
             randomFirst:  "b97kj"
             randomSecond: "87ayI"
             randomThird: "AG9bw"

I have attached the code below. I'm done with uploading the data to the database which has

CEVM-->Random-->bkIG89-BX78BkuO(ID)-->randomOne,randomTwo,randomThree

In another activity I have a Edit Text, Button and a Text View. User needs to enter the ID (in the above example 'bkIG89-BX78BkuO') and when the button is pressed, data under that ID(values of randomOne, randomTwo, randomThree) should be displayed in TextView.

For uploading data to Firebase:

public String addRandom(){
    String firstRandom = randomOne.getText().toString();
    String secondRandom = randomTwo.getText().toString();
    String thirdRandom = randomThree.getText().toString();

    String id = databaseRandom.push().getKey();
    randomNumber random = new randomNumber(firstRandom,secondRandom,thirdRandom);
    databaseRandom.child(id).setValue(random);
    String code = id;
    return code;
}

For retrieving:(I tried, but im not sure what should be done)

mVerifyBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String dataInput = mSearch.getText().toString();

            reference = FirebaseDatabase.getInstance().getReference().child(dataInput);

        }
    });
}

public void buttonClick(View view){
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String randomOne = dataSnapshot.child("randomFirst").getValue().toString();
            mViewData.setText(randomOne + randomTwo + randomThree);
        }

I expect the output should be the value of randomOne, randomTwo and randomThree, but nothing is been displayed so far.

Upvotes: 1

Views: 399

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80924

If dataInput is equal to the id (-bKIG89-BX78BkuO) in the database, then you need to change your reference to the following:

reference = FirebaseDatabase.getInstance().getReference().child("CEVM").child("Random").child(dataInput);

You should traverse the database from top node to the attribute where you need to retrieve the data.

Upvotes: 1

Related Questions