Nguyễn Tuấn Kiệt
Nguyễn Tuấn Kiệt

Reputation: 220

How to get value in Firebase

My database:

enter image description here

I got "Code". I try to get "ClassID" (Ex: Code=1235, I want a String ClassID= "12"):

Here my code:

  private void checkCode(){
        String userCode = inputCode.getText().toString().trim();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Assignment");
        Query checkCode = reference.orderByChild("Code").equalTo(userCode);
        checkCode.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists()){
                    String classID; // I think here
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }

How to do that?

Upvotes: 1

Views: 78

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

If you want to search the database for all objects that have the "Code" property set to "1235" and then get the value of "classID", please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference assignmentRef = rootRef.child("Assignment");
Query codeQuery = assignmentRef.orderByChild("Code").equalTo("1235");
codeQuery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String classID = ds.child("classID").getValue(String.class);
                Log.d("TAG", "ClassID: " + classID);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be:

ClassID: 12

The exact value you are looking for. Remember that each time you query the database, you need to loop through the results using .getChildren() method, in order to get the results.

Upvotes: 1

Related Questions