Searchview in Listview Having a Custom Adapter

SearchView In ListView having a custom Adapter

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;
}
}

Search items from listview with custom adapter

You should implements Filterable in your Adapter

android : adding SearchView inside a Custom ListView with Custom Adapter

Try this adapter code:

public class IndividualsAdaptor extends ArrayAdapter {
protected Context mContext;
// Code for Custom Filter.
protected List mBackupList = new ArrayList();

public IndividualsAdaptor(Context context, List status) {
super(context, R.layout.t3, status);
mContext = context;
// Code for Custom Filter.
mBackupList.addAll(status);
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.t3, null);
holder = new ViewHolder();
holder.usernameHomepage = (TextView) convertView.findViewById(R.id.fname);
holder.statusHomepage = (TextView) convertView.findViewById(R.id.lname);
holder.pposition = (TextView) convertView.findViewById(R.id.idposition);
holder.orgName = (TextView) convertView.findViewById(R.id.organizationname);
holder.logo = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

ParseObject statusObject = (ParseObject) getItem(position);
// title
String username = statusObject.getString("firstname");
holder.usernameHomepage.setText(username);
// content
String status = statusObject.getString("lastname");
holder.statusHomepage.setText(status);
// content
String positions = statusObject.getString("position");
holder.pposition.setText(positions);
// content
String org = statusObject.getString("organizationName");
holder.orgName.setText(org);
// logo
URL url = null;
Bitmap bmp = null;
try {
url = new URL("img hosting location" + statusObject.getString("image"));
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
}catch (IOException e) {
}
holder.logo.setImageBitmap(bmp);
Picasso.with(mContext)
.load(String.valueOf(url))
.into(((ImageView) convertView
.findViewById(R.id.imageView)));

return convertView;
}

public static class ViewHolder {
TextView usernameHomepage;
TextView statusHomepage;
TextView orgName;
TextView pposition;
ImageView logo;
}

// Code for Custom Filter.
@Override
public Filter getFilter() {return new Filter(){
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String queryString = charSequence.toString().toLowerCase();
List<ParseObject> filteredList = new ArrayList<>();
ParseObject tmpItem;
String tmpUsername, tmpStatus, tmpPositions, tmpOrg;
for(int i=0; i<mBackupList.size(); i++){
tmpItem = (ParseObject) mBackupList.get(i);
tmpUsername = tmpItem.getString("firstname").toLowerCase();
tmpStatus = tmpItem.getString("lastname").toLowerCase();
tmpPositions = tmpItem.getString("position").toLowerCase();
tmpOrg = tmpItem.getString("organizationName").toLowerCase();
// The matching condition
if(tmpUsername.contains(queryString)||tmpStatus.contains(queryString)||
tmpPositions.contains(queryString)||tmpOrg.contains(queryString)){
filteredList.add(tmpItem);
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filteredList.size();
filterResults.values = filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, Filter.FilterResults filterResults) {
clear();
addAll((List<ParseObject>) filterResults.values);
}
};}

public void updateBackupList(List newList){
mBackupList.clear();
mBackupList.addAll(newList);
}
}

And Individuals.java:

public class Individuals extends ListFragment {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
SearchView sv;
IndividualsAdaptor adaptor;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.individuals, container, false);
}

@Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
sv = (SearchView) view.findViewById(R.id.searchView1);
adaptor = new IndividualsAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
ParseQuery.getQuery("_User").findInBackground(this);

sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
return false;
}
@Override
public boolean onQueryTextChange(String text) {
adaptor.getFilter().filter(text);
return true;
}
});
}

@Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " _User");
mOrganization.clear();
mOrganization.addAll(scoreList);
((IndividualsAdaptor) getListAdapter()).updateBackupList(mOrganization);
((IndividualsAdaptor) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}

Filtering a ListView with SearchView and custom adapter

getView() and other functions retrieve always from customArrayList and never from filteredArrayList.



Related Topics



Leave a reply



Submit