How to search data in Firebase?

后端 未结 2 2044
感情败类
感情败类 2021-01-23 18:20
Bundle bundle = getIntent().getExtras();
   String name = bundle.getString(\"name\");

   mValueView = (TextView) findViewById(R.id.textView);

   mRef = FirebaseDatabas         


        
2条回答
  •  轮回少年
    2021-01-23 18:55

    There are two problems in your code:

    1. you're specifying the child node Users twice
    2. a query results a list of results, which your onDataChange doesn't handle

    specifying the child node Users twice

    mRef = FirebaseDatabase.getInstance()
             .getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/Users");
                                                                   // ^^^^^ 
    
    Query query = mRef.child("Users").orderByChild("title").equalTo(name);
                           // ^^^^^ 
    

    Easily fixed:

    mRef = FirebaseDatabase.getInstance()
             .getReferenceFromUrl("https://mymap-3fd93.firebaseio.com/");
    
    Query query = mRef.child("Users").orderByChild("title").equalTo(name);
    

    I'm not sure why you use getReferenceFromUrl() to begin with. For most applications, this accomplishes the same is simpler:

    mRef = FirebaseDatabase.getInstance().getReference();
    

    a query results a list of results

    When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

       query.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange(DataSnapshot dataSnapshot) {
               for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                   System.out.println(snapshot.getKey());
                   System.out.println(snapshot.child("title").getValue(String.class));
               }
           }
    
           @Override
           public void onCancelled(DatabaseError databaseError) {
               throw databaseError.toException();
           }
       });
    

提交回复
热议问题