Retrieving data from Firebase Realtime Database in Android

前端 未结 3 1055
情歌与酒
情歌与酒 2020-12-03 22:45

I\'m new to Firebase and NoSQL. I have an Android Demo, with a City Autocomplete Text Field in which I want to populate the cities I have from my Firebase DB, while typing.<

3条回答
  •  旧巷少年郎
    2020-12-03 23:06

    @NicholasChen has identified the problem. But here's the way you'd implement using the 3.x SDK:

    DatabaseReference cities = databaseRef.child("cities")
    Query citiesQuery = cities.orderByKey().startAt(input).endAt(input+"\uf8ff");
    citiesQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List cities = new ArrayList();
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                cities.add(postSnapshot.getValue().toString());
            }
    

    By starting at the user input and ending at the last string that starts with the user input, you get all matching items

    For relatively short lists of items Ryan's approach will also work fine. But the above Firebase query will filter server-side.

    Update

    I just ran this code:

        DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("39714936");
    
        String input = "G";
    
        DatabaseReference cities = databaseRef.child("cities");
        Query citiesQuery = cities.orderByKey().startAt(input).endAt(input + "\uf8ff");
        citiesQuery.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List cities = new ArrayList();
    
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    cities.add(postSnapshot.getValue().toString());
                }
                System.out.println(cities);
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    

    And it printed:

    true

    true

    So clearly matches two cities.

    Feel free to test against my database: https://stackoverflow.firebaseio.com/39714936

提交回复
热议问题