Home > Blockchain >  How can I get distinct items from firebase to spinner in android?
How can I get distinct items from firebase to spinner in android?

Time:07-20

I am trying to fill a spinner with categories, I manage to iterate every category in my database and add it to the spinner but I need to fetch only distinct values, see this image;

enter image description here

This is my code;

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            final List<String> categorySpinner = new ArrayList<>();

            for (DataSnapshot childSpinner : snapshot.getChildren()) {
                String spinnerCat = childSpinner.child("category").getValue(String.class);

                categorySpinner.add(spinnerCat);

            }

            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(LineChartActivity.this, R.layout.spinner_item, categorySpinner);
            arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            spinner_2.setAdapter(arrayAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

CodePudding user response:

It's simple, simply change the line:

categorySpinner.add(spinnerCat);

to

if (!categorySpinner.contains(spinnerCat)) {
    categorySpinner.add(spinnerCat);
}

Happy coding.

  • Related