Home > Mobile >  Get Value From Realtime Firebase Inside Child
Get Value From Realtime Firebase Inside Child

Time:08-04

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

CodePudding user response:

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.
  • Related