Search code examples
javaandroidarraylistandroid-filter

ArrayList filtering not working: Android


I have an array list that displays a list of companies. Each of these companies is having town names related to it. What I have done is that I am creating buttons for each of the town names such that when I click on any of the town names, the ArrayList should be filtered and only the companies with that town names should be displayed.

I am creating buttons like,

        stringList.add(tempList.get(n).getTownName());
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 60));
        btnTag.setText(stringList.get(k));
        btnTag.setBackgroundResource(R.drawable.alpha_button_selector);
        btnTag.setClickable(true);
        townLayout.addView(btnTag);

On clicking the button I am calling the method to filter the data,

        btnTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                locationFilter(stringList,length);
            }
        });

For filtering the data, I am creating a new ArrayList to store the filtered data such as,

        ArrayList<CompanySearchResult> secondList = new ArrayList<CompanySearchResult>();

        for (CompanySearchResult a : tempList) {
            for (int k = 0; k < length; k++) {

                if (a.getTownName.equalsIgnoreCase(stringList.get(k))) {
                    secondList.add(a);
                }
            }
        }

        tempList.clear();
        tempList.addAll(secondList);

What I am actually trying to do is filtering the temp list according to the town names when the button is clicked.

I have researched on this but could not fix the issue. Can anyone tell me what am I doing wrong and how can I filter the list.


Solution

  • The issue here was since the buttons were getting created programmatically based on the number of town names(duplicates eliminated), the stringList.get(k), was not giving me the town name correctly corresponding to the button clicked.

    Thus, on clicking the button, I fetched the text in the button as it displays the town name and then passed that to the method to filter the data,

        btnTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence name = btnTag.getText();
                locationFilter(name);
            }
        });
    

    In my filter method, I changed to,

            ArrayList<ACompanyForSearchResult> filtered = new ArrayList<ACompanyForSearchResult>();
    
            for (ACompanyForSearchResult town : tempList) {
    
                if (town.getTownName().equals(name)) {
                    filtered.add(town);
                }
            }
    
            tempList.clear();
            tempList.addAll(filtered);
            listAdapter.notifyDataSetChanged();