How to search data in Firebase?

后端 未结 2 2018
感情败类
感情败类 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:52

    If you want to search title value only one time, without listening for updates, you can simply use :

    ref.addListenerForSingleValueEvent(
                        new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
        }});
    

    Then if you get a reference to 'Users' you can do some logic with iteration, for example :

    for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
        String title = (String) singleSnapshot.child("title").getValue();
                            //do your logic
                        }
    
    0 讨论(0)
  • 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();
           }
       });
    
    0 讨论(0)
提交回复
热议问题