I want to do a search function of child items in Expandable List View. I have a hashMap of type (String, List String) for the child items, where List String contains all the child items. However, I could not figure out how to filter the data from the list to use in my search query.
I have tried some methods from stackoverflow posts : Search a HashMap in an ArrayList of HashMap , How to use edit text as search box in expandable listview android? and few others, but of no help.
MainActivity.java
List<String> listP = new ArrayList<>();
HashMap<String, List<String>> listC = new HashMap<>();
ExpandableListAdapter expandableListAdapter = new ExpandableListAdapter(this, listP, listC, this);
listP.add("Movie");
listP.add("Building");
listP.add("Car");
List <String> movie = new ArrayList<>();
movie.add("horror");
movie.add("action");
List <String> building = new ArrayList<>();
building.add("bank");
building.add("hotel");
List <String> car = new ArrayList<>();
car.add("BMW");
car.add("Mercedes");
listC.put(listP.get(0),movie);
listC.put(listP.get(1),building);
listC.put(listP.get(2),car);
ExpandableListAdapter.java
List<String> listDataHeader;
private HashMap<String, List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap, Activity activity) { this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
this.activity = activity;
}
public void filterData(String query)
{
query = query.toLowerCase();
listDataHeader.clear();
if(query.isEmpty())
{
listDataHeader.clear();
}
else // if user writes something
{
// I don't know how to get the values from the child items to compare it with query
}
}
Try this:
List<String> listDataHeader;
List<String> backupHeader;
private HashMap<String, List<String>> listHashMap; // Backup lists.
private HashMap<String, List<String>> backupHashMap;
public void filterData(String query)
{
if(backupHeader == null){ // Save original lists for the first time.
backupHeader = new ArrayList<>();
backupHeader.addAll(listDataHeader);
backupHashMap = new HashMap<>();
backupHashMap.putAll(listHashMap);
}
query = query.toLowerCase();
listDataHeader.clear();
listHashMap.clear();
if(query.isEmpty())
{
listDataHeader.addAll(backupHeader);
listHashMap.putAll(backupHashMap);
}
else // if user writes something
{
for(String header: backupHeader) {
List<String> tmpList = new ArrayList<>();
for(String item:backupHashMap.get(header)){
if(item.toLowerCase().contains(query)) tmpList.add(item);
}
if(tmpList.size() > 0){
listDataHeader.add(header);
listHashMap.put(header, tmpList);
}
}
}
notifyDataSetChanged();
}
Hope that helps!