且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Android 中的 Firebase 实时数据库中检索数据

更新时间:2022-06-03 03:20:51

@NicholasChen 已发现问题.但这是您使用 3.x SDK 实现的方式:

@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<String> cities = new ArrayList<String>();
        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

对于相对较短的项目列表,Ryan 的方法也可以正常工作.但是上面的 Firebase 查询会过滤服务器端.

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

我刚刚运行了这段代码:

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<String> cities = new ArrayList<String>();

            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                cities.add(postSnapshot.getValue().toString());
            }
            System.out.println(cities);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

它打印出来了:

是的

是的

如此明显地匹配两个城市.

So clearly matches two cities.

随意对我的数据库进行测试:https://***.firebaseio.com/39714936

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