SearchView In ListView having a custom Adapter

AndroidMech picture AndroidMech · May 2, 2014 · Viewed 59.6k times · Source

Guys I am in need of some help.I have been trying to implement a SearchView in my project.But my project contains a listview with a custom adapter attached to it..I have searched many sites but all have examples implemented using an arrayadapter..Lets say I have an Employee class and it contains name and age fields..How to I filter the employees using their Name only..

public class MainActivity extends Activity implements SearchView.OnQueryTextListener
{
SearchView mSearchView;
ListView mListView;
//String mStrings[]= {"abc","def","efg","ghi","ijk","apple","agxhsdgc","abbbcc"};
ArrayList<Employee> emp_list=null;
EmployeeAdapter emp_adapter=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSearchView=(SearchView) findViewById(R.id.searchView1);
        mListView=(ListView) findViewById(R.id.listView1);

        emp_list=new ArrayList<Employee>();
        emp_list.add(new Employee("ABC", 24));
        emp_list.add(new Employee("ACB", 24));
        emp_list.add(new Employee("BVF", 28));
        emp_list.add(new Employee("BRT", 28));
        emp_list.add(new Employee("ANM", 23));

        emp_adapter=new EmployeeAdapter(MainActivity.this, emp_list);
        mListView.setAdapter(emp_adapter);

//      mListView.setAdapter(new ArrayAdapter<String>(this,
//                android.R.layout.simple_list_item_1,
//                mStrings));
        mListView.setTextFilterEnabled(true);
        setupSearchView();


    }
     private void setupSearchView() 
     {
            mSearchView.setIconifiedByDefault(false);
            mSearchView.setOnQueryTextListener(this);
            mSearchView.setSubmitButtonEnabled(true); 
            mSearchView.setQueryHint("Search Here");
        }

        @Override
        public boolean onQueryTextChange(String newText) 
        {

            if (TextUtils.isEmpty(newText.toString())) {
                mListView.clearTextFilter();
            } else {
                mListView.setFilterText(newText.toString());
            }
            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) 
        {
            return false;
        }


    }

and this is my adapter class that extends BaseAdapter..

public class EmployeeAdapter extends BaseAdapter {

    Context ctx;
    ArrayList<Employee> emp_list;
    LayoutInflater linf=null;
    EmployeeHolder holder=null;






    public EmployeeAdapter(Context ctx, ArrayList<Employee> emp_list) {
        super();
        this.ctx = ctx;
        this.emp_list = emp_list;
        linf=(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public class EmployeeHolder
    {
        TextView name;
        TextView age;

    }



    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return emp_list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return emp_list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        if(convertView==null)
        {
            convertView=linf.inflate(R.layout.row, parent, false);
            holder=new EmployeeHolder();
            holder.name=(TextView) convertView.findViewById(R.id.name);
            holder.age=(TextView) convertView.findViewById(R.id.age);

            convertView.setTag(holder);
        }
        else
        {
            holder=(EmployeeHolder) convertView.getTag();
        }

        Employee e=(Employee) getItem(position);


        holder.name.setText(e.getName());
        holder.age.setText(String.valueOf(e.getAge()));

        return convertView;

    }

}

Thanks in Advance..

Answer

Haresh Chhelana picture Haresh Chhelana · May 2, 2014

Try this way,hope this will help you...

activity_main.xml

    <SearchView
        android:id="@+id/searchView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>


</LinearLayout>

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txtAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"/>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity implements SearchView.OnQueryTextListener
{
    private SearchView mSearchView;
    private ListView mListView;
    private ArrayList<Employee> employeeArrayList;
    private EmployeeAdapter employeeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSearchView=(SearchView) findViewById(R.id.searchView1);
        mListView=(ListView) findViewById(R.id.listView1);

        employeeArrayList=new ArrayList<Employee>();
        employeeArrayList.add(new Employee("ABC", 24));
        employeeArrayList.add(new Employee("ACB", 24));
        employeeArrayList.add(new Employee("BVF", 28));
        employeeArrayList.add(new Employee("BRT", 28));
        employeeArrayList.add(new Employee("ANM", 23));

        employeeAdapter=new EmployeeAdapter(MainActivity.this, employeeArrayList);
        mListView.setAdapter(employeeAdapter);

        mListView.setTextFilterEnabled(true);
        setupSearchView();


    }
    private void setupSearchView()
    {
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(true);
        mSearchView.setQueryHint("Search Here");
    }

    @Override
    public boolean onQueryTextChange(String newText)
    {

        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
        } else {
            mListView.setFilterText(newText);
        }
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query)
    {
        return false;
    }


}

EmployeeAdapter.java

public class EmployeeAdapter extends BaseAdapter implements Filterable {

    public Context context;
    public ArrayList<Employee> employeeArrayList;
    public ArrayList<Employee> orig;

    public EmployeeAdapter(Context context, ArrayList<Employee> employeeArrayList) {
        super();
        this.context = context;
        this.employeeArrayList = employeeArrayList;
    }


    public class EmployeeHolder
    {
        TextView name;
        TextView age;
    }

    public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<Employee> results = new ArrayList<Employee>();
                if (orig == null)
                    orig = employeeArrayList;
                if (constraint != null) {
                    if (orig != null && orig.size() > 0) {
                        for (final Employee g : orig) {
                            if (g.getName().toLowerCase()
                                    .contains(constraint.toString()))
                                results.add(g);
                        }
                    }
                    oReturn.values = results;
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                employeeArrayList = (ArrayList<Employee>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }


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

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

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        EmployeeHolder holder;
        if(convertView==null)
        {
            convertView=LayoutInflater.from(context).inflate(R.layout.row, parent, false);
            holder=new EmployeeHolder();
            holder.name=(TextView) convertView.findViewById(R.id.txtName);
            holder.age=(TextView) convertView.findViewById(R.id.txtAge);
            convertView.setTag(holder);
        }
        else
        {
            holder=(EmployeeHolder) convertView.getTag();
        }

        holder.name.setText(employeeArrayList.get(position).getName());
        holder.age.setText(String.valueOf(employeeArrayList.get(position).getAge()));

        return convertView;

    }

}

Employee.java

public class Employee {

    private String name;
    private int age;

    public  Employee(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }
}