Stefano Tokyo
Stefano Tokyo

Reputation: 85

Querying by range in firebase

I have a range slider for prices of food , and based on the min and max of the slider , I want to display the foods which are in this range.

Slider code

multiSlider.setOnThumbValueChangeListener(new MultiSlider.SimpleChangeListener() {
    @Override
    public void onValueChanged(MultiSlider multiSlider, MultiSlider.Thumb thumb, int thumbIndex, int value) {
        if (thumbIndex == 0) {
            min = String.valueOf(value);
            min1.setText(min);
        } else {
            max = String.valueOf(value);
            max1.setText(max);
        }
    }
});

alertD.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        SearchPrice(min, max);
    }
});

Query Code

private void SearchPrice(String min, String max) {
    Query searchByName = foodList.orderByChild("price").startAt(min).endAt(max);
    FirebaseRecyclerOptions<Food> foodOptions = new FirebaseRecyclerOptions.Builder<Food>().setQuery(searchByName, Food.class).build();

    Searchadapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(foodOptions) {
        @Override
        protected void onBindViewHolder(@NonNull FoodViewHolder viewHolder, int position, @NonNull Food model) {
            viewHolder.food_name.setText(model.getName());
            viewHolder.food_price.setText(model.getPrice());

Structure

enter image description here

I tried using the startAt and endAt , but its displaying food with prices outside of the range.Any help on this please ? Is there another way of doing this type of query?

Upvotes: 0

Views: 1166

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

You're storing numeric values as strings in the database. Firebase sorts strings lexicographically. In lexicographical order of you have number from 1 to 12, they are sorted as "1", "10", "11", "12", "2", "3", "4", "5", "6", "7", "8", "9". So the range from "1" to "10" is precisely those two "numbers".

To solve this problem, store your numeric values as actual numbers in the database.

Also see:

Upvotes: 2

Related Questions