zimspy
zimspy

Reputation: 146

Search and Filter Android ListView

I am having a problem filtering an Android ListView using a search-bar. Before I expanded my code and added a CustomList class it worked okay. The CustomList class is for populating the ListView that contains Images and sub-text. My CustomList class extends ArrayAdapter.

This is the relevant code from both classes

public class CustomList extends ArrayAdapter<String> {

private final Activity context;
private final String[] languages;

public CustomList(Activity context, String[] languages) {
    super(context, R.layout.list_single, languages);
    this.context = context;
    this.languages = languages;
}
}

and the MainActivity:

public class MainActivity extends Activity {

CustomList adapter;
ListView list;
EditText searchBar;

String[] languages = { "ActionScript", "Ajax", "Python", "Java", "JavaScript", "C++", "C#", "C", "NASM", "Assembly",
        "PHP", "R", "Scala", "TeX", "Visual Basic", "Fortran", "COBOL", "Lisp", "Lua", "Ruby", "XML", };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Arrays.sort(languages);

    searchBar = (EditText) findViewById(R.id.searchBarTI);

    adapter = new CustomList(MainActivity.this, languages);
    list = (ListView) findViewById(R.id.listVw);
    list.setTextFilterEnabled(true);

    list.setAdapter(adapter);

    searchBar.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            MainActivity.this.adapter.getFilter().filter(cs);
        }
    });
}
}

When I enter text into the search-bar, only the first element in the listView is left. The rest are filtered out:

Image of the bug

I am not sure what I am leaving out or not seeing. Someone please assist.

Upvotes: 1

Views: 77

Answers (1)

Mavya Soni
Mavya Soni

Reputation: 982

If you are customizing the ArrayAdapter then you should implement a filterable interface for searching data in adapter.

Check out below link : Custom getFilter in custom ArrayAdapter in android

Upvotes: 1

Related Questions