I am storing a list of users in Firebase. The structure looks like this:
In my Android app, I want to let the user search for any user in a flexible manner. So John Smith should show up in the results if the user searches for things like: Joh..., Smit..., jsmi.... Also, I want the search to show results instantly as the user types (like Instagram).
Currently, this is my implementation. I pull all the user details when the search activity opens up and store all details in an ArrayList
. Then when user starts searching, I search the ArrayList
and returns the matches.
Below is some sample code:
ArrayList<User> listOfUsers = new ArrayList<>();
ref.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
User user = userSnapshot.getValue(User.class);
listOfUsers.add(user);
}
}
@Override
public void onCancelled(DatabaseError databaseError) { }
});
// Then I search for users like this
for (User user : listOfUsers) {
if (user.getFullname.contains("Joh") ||
user.getUsername.contains("Joh")){
// show user in results
}
}
It works fine right now because I don't have too many users. But I feel that if I have 100k users, pulling all their details before hand and parsing the arrayList of 100k items to look for matches might be expensive. What would be a better solution?