How can I filter ListView data when typing on EditText in android

Viewed 53815

I have a ListView and a EditText. How can I filter ListView data when typing on EditText?

6 Answers

when you use custom listView

Adapter :

public class Adapter extends ArrayAdapter {
ArrayList<String> list = new ArrayList<>();
ArrayList<String> filteredData = new ArrayList<>();

public Adapter(@NonNull Context context, int resource) {
    super(context, resource);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    @SuppressLint("ViewHolder") View vi = inflate.inflate(R.layout.ly_items, null);
    try {
        JSONObject js = new JSONObject(list.get(position));
        TextView txtItem = vi.findViewById(R.id.txtItem);
        ImageView imgItem = vi.findViewById(R.id.imgItem);
        txtItem.setText(js.getString("name") + " - " + js.getInt("number"));
        Picasso.get().load(js.getString("logo_url")).into(imgItem);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return vi;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object.toString());
    filteredData.add(object.toString());
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}


public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    list.clear();
    if (charText.length() == 0) {
        list.addAll(filteredData);
    } else {
        for (String wp : filteredData) {

            try {
                JSONObject json = new JSONObject(wp);
                if (json.getString("name").toLowerCase().contains(charText) || json.getString("number").contains(charText)) {
                    list.add(wp);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    notifyDataSetChanged();
    }
}

And your class:

 Adapter adapter;
ListView list;
EditText edtSearch;

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

list = findViewById(R.id.list);

edtSearch = findViewById(R.id.edtSearch);

 adapter = new Adapter(this, android.R.layout.simple_list_item_1);


list.setAdapter(adapter);

edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.filter(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }
Related