Get Value From Realtime Firebase Inside Child

Issue

Greeting everyone, im working a project right now and need help for firebase realtime database.

My firebase Project

enter image description here
As you guys can see in the above picture, inside student, I have matric number, and inside matric number have block and department.

I have a barcode scanner which scan the value of department and return to get the matric number. Any solution.

Below code is my progress.

mCodeScanner.setDecodeCallback(new DecodeCallback() {
        @Override
        public void onDecoded(@NonNull final Result result) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    r = result.getText();
                    Query s = ref.equalTo("JTMK", "department");
                    name.setText(r);
        }});}});

Solution

If you don’t know the matric number of the student, indeed a query is required. Assuming that result.getText() returns JTMK, please use the following lines of code:

mCodeScanner.setDecodeCallback(new DecodeCallback() {
    @Override
    public void onDecoded(@NonNull final Result result) {
        String department = result.getText();
        DatabaseReference db = FirebaseDatabase.getInstance().getReference();
        DatabaseReference studentRef = db.child("Student");
        Query queryByDepartment = studentRef.orderByChild("department").equalTo(department).limitToFirst(1);
        queryByDepartment.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (task.isSuccessful()) {
                    for (DataSnapshot ds : task.getResult().getChildren()) {
                        String block = ds.child("block").getValue(String.class);
                        name.setText(block);
                        Log.d("TAG", block);
                    }
                } else {
                    Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
                }
            }
        });
    }
});

Things to notice:

  1. There is no need to use runOnUiThread when reading data from the Realtime Database.
  2. Firebase API is asynchronous. So I recommend you read the following resource:
  3. When you run the code, you should see in the logcat BESTARI 4, which will also be set to name TextView.

Answered By – Alex Mamo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published