Search code examples
androidsqlitelistviewandroid-edittextsearchable

How to insert a filter in my EditText in a ListView to filter my Database


I have a ListView with an EditText to prompt a simple query making a select in my database, and i need to implements this query in my TextWatcher {... but I don't know how to do that any ideas ??

And I need to query two columns in one table...

public class ListaMateriais extends Activity {

private ListView listamateriais;
ArrayAdapter<String> adapMatchMaterial;
EditText inputSearch;
public EditText ETclient; 
ArrayList<HashMap<String, String>> productList;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_material_match);

    String products[] = { "Parafuso 3x4 092387",
                      "Cabeçote redpo 09873",  
                      "alavanca de ignição 027625", 
                      "Pistão de arranque 093298092",  
                      "Eixo dianteiro 0343232", 
                      "Cabeçote parafuseta 093232" }; 
    listamateriais = (ListView) findViewById(R.id.list_match_material);
    adapMatchMaterial = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
    listamateriais.setAdapter(adapMatchMaterial);

    listamateriais.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View v, int position,  long arg3) {
            String text= (String) arg0.getItemAtPosition(position);
            Bundle bundle = new Bundle();
            bundle.putString("TextMateriais", text);
            Intent int_material = new Intent(ListaMateriais.this,Formulario_ItemNota.class);
            int_material.putExtras(bundle);
            startActivity(int_material);
            finish();
        } 
    }); 

    inputSearch = (EditText) findViewById(R.id.materialSearch); 
    inputSearch.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            ListaMateriais.this.adapMatchMaterial.getFilter().filter(cs);
        } 
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        } 
        public void afterTextChanged(Editable arg0) {
        } 
    }); 
} 

Any helps will be truly appreciated... Thanks


Solution

  • Use AutoCompleteTextView

    AutoCompleteTextView atxtSearch = (AutoCompleteTextView) findViewById(R.id.atxtSearchUser);
    atxtSearch.setThreshold(3);
    ArrayAdapter<String> adapMatchMaterial = new ArrayAdapter<String>(this,
    android.R.layout.simple_dropdown_item_1line,products); //products should be an array
    atxtSearch.setAdapter(adapMatchMaterial );
    

    Then When you type on this edit text, after typing 3 letters, it will automatically list the items