Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
48 views
in Technique[技术] by (71.8m points)

java - Android get data from Firebase

I'd like to build a question system. Each question has a category, for example, questions about painting, about music.

My Firebase schema is like this:

enter image description here

So I'd like to get questions about music, I tried:

mDatabase.child("questions").child("music").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            // Get question value
            Questions questions = dataSnapshot.getValue(Questions.class);
            String question = questions.getQuestion();
            Toast.makeText(MainActivity.this, question, Toast.LENGTH_LONG).show();
        }

But my toast is empty. Any ideas why?

I also have Questions.java:

public class Questions {

        public String question;

        public Questions() {
            // Default constructor required for calls to DataSnapshot.getValue(User.class)
        }

        public Questions(String question) {
            this.question = question;
        }

        public String getQuestion(){
            return question;
        }

}
question from:https://stackoverflow.com/questions/65890647/android-get-data-from-firebase

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When using the following reference:

mDatabase.child("questions").child("music")

You are telling Firebase Realtime Database to return all elements that exist under the following hierarchy:

Firebase-root -> questions -> music

You will always get no elements because such a path doesn't exist. I say that because between the "questions" node and the "music" property there is a child missing, which that ID. There two approaches that can help you solve this.

In the first one, you keep your actual schema, without making any change and use the following lines of code, to get, for example, all music questions:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference questionsRef = rootRef.child("questions");
Query query = questionsRef.orderByChild("music");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("music").getValue(String.class);
            if (music != null) {
                Log.d(TAG, name);
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be:

What kind of music do you like?
Which is more important to you, music or TV?

The second approach would be to create a POJO class like this:

class Question {
    public String type, name;
}

Using this approach, you need to change the database schema a little bit, as explained below:

 Firebase-root
    |
    --- questions
           |
           --- 84384238423842
           |     |
           |     --- type: "music"
           |     |
           |     --- name: "What kind of music do you like?"
           |
           --- 8rs8842348234
                 |
                 --- type: "music"
                 |
                 --- name: "Which is more important to you, music or TV?"

In this way, the following code is required:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference questionsRef = rootRef.child("questions");
Query query = questionsRef.orderByChild("type").equalTo("music");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Question question = ds.getValue(Question.class);
            Log.d(TAG, question.name);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be the same as above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...