Reputation: 3405
I wanted to write a query so as to filter the data using an edittext, the code below does work but bring all of the unwanted searched data. Can you please help me? The JSON object is as follows: The data I wanted to filter out is the username
public class SearchActivity extends AppCompatActivity {
ListView searchList;
DatabaseReference databaseReference;
FirebaseListAdapter<SearchDetails> listAdapter;
String search;
EditText editTextSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
searchList = (ListView) findViewById(R.id.listViewSearch);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Search Users");
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
editTextSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
search = editTextSearch.getText().toString();
if (search.equals("")){
searchList.setAdapter(null);
}else{
searchList.setAdapter(listAdapter);
}
}
});
Query query = databaseReference.startAt(search).endAt(search+"~").limitToFirst(10);
listAdapter = new FirebaseListAdapter<SearchDetails>(
this,
SearchDetails.class,
R.layout.search_layout,
query
) {
@Override
protected void populateView(View v, SearchDetails model, int position) {
TextView username = (TextView) v.findViewById(R.id.textViewUsername);
username.setText(model.getUsername());
TextView name = (TextView) v.findViewById(R.id.textViewName);
name.setText(model.getName());
}
};
}
}
Upvotes: 1
Views: 997
Reputation: 2307
In order to solve this problem we need to understand a few things about Firebase, that a lot of developers might overlook.
The problem that I think you have at hand is to "have an EditText
that allows user to search for usernames of your users.
How I would suggest you to tackle this is by flattening the structure of your data like so
You can have objects inside usernames
array. Each object's key is the username
and the value is another object with an empty-key : ""
like so.
And you can then have another array of users
where again the keys are usernames
and rest of the data lives as an object under it.
Now you can easily run your Filter Query on usernames
without worrying about the overhead of fetching unnecessary data in that query.
And once you know which username
was selected, you can query users
to fetch that exact user
from the array.
Upvotes: 1
Reputation: 67
Query query = databaseReference.orderByChild("username").startAt(search).endAt(search+"~").limitToFirst(10);
Upvotes: 0