user2514575 user2514575 - 4 months ago 61
Java Question

Filtering a ListView of objects with a Spinner by a value within the object for Android

Hello in my project I have made an object class called "Program" with many values such as one, an array called "Category." All the programs are displayed by a

ListView
and have a set category
Spinner
in the layout (with the purpose of categorizing the programs with the matching categories).

I have this piece of code:

final ArrayAdapter spinnerAdapter = new ArrayAdapter(getActivity(), R.layout.layout_spinner, MainActivity.categories); //MainActivity.categories is an array filled with strings

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

String text = spinner.getSelectedItem().toString();
listAdapter.getFilter().filter(text);
listAdapter.notifyDataSetChanged();
}


Program.java

public class Program {

public String programName;
public ArrayList<String> categories;

.....

public ArrayList<String> getCategories () {
return categories;
}

public String toString() {
return programName;
}
}


But this only filters according to the text on the list, how can I get it to filter it by the
Category
variable in the list of Programs?

Answer

Well,

First take a look here and understand a bit about filtering:

Adapter filtering android

Next, I think in your case you have to do the following:

@Override
protected FilterResults performFiltering(CharSequence constraint) {
     FilterResults results = new FilterResults();
    // We implement here the filter logic
    if (constraint == null || constraint.length() == 0) {
        // No filter implemented we return all the list
         results.values = yourList;
         results.count = yourList.size();
    }
    else {
    // We perform filtering operation
    List<Program> finalList = new ArrayList<Program>();
    //here think of something regarding the upper and lower cases.
    for (Program p : yourList) {            
        if(p.getCategories().
              contains(constraint.toString()))
         finalList.add(p);
    }

     results.values = finalList;
     results.count =  finalList.size();
   }
   return results;
}
Comments