Retrieving data from Firebase Realtime Database in Android

前端 未结 3 1057
情歌与酒
情歌与酒 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:17

    Try something like this to iterate over the children in the cities snapshot and add all the cities to an ArrayList of Strings.

    ArrayList cityList = new ArrayList<>();
    
    databaseRef.child("cities").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            cityList.clear();
            for (DataSnapshot data : dataSnapshot.getChildren()){
                cityList.add(data.getKey);
            }
    
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "getUser:onCancelled", databaseError.toException());
            // ...
        }
    });
    

    Editing this paragraph for clarity:

    This will get all your cities read into the program memory so you can use that data to display the cities to the user. If the city list changes, so will the data the user sees. If the user is not online, this will not work. This puts a real time, online only listener on the database.

    The logic in my mind is something like:

    1. Set a value listener on the text box.
    2. When user types, make a view display all the items in the array list that start with the same substring that was typed.
    3. Handle arrayIndex errors of course.

    Hopefully this will get you on the right track. I am sure there are other ways you could implement it but this is what I would personally do. If you need help with the code to display the correct cities, start a chat with me and I can brainstorm with you.

提交回复
热议问题