How could i filter the listview using baseadapter
MainActivity.java
public class MainActivity extends Activity {
private ListView mListView;
private CustomAdapter mCustomAdapter;
private EditText mEditText;
private ArrayList<Contacts> _Contacts = new ArrayList<Contacts>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 100; i++) {
Contacts contacts = new Contacts();
contacts.setId(""+i);
contacts.setName("Name "+i);
_Contacts.add(contacts);
}
mListView = (ListView) findViewById(R.id.listView1);
mEditText = (EditText) findViewById(R.id.editText1);
mCustomAdapter = new CustomAdapter(MainActivity.this, _Contacts);
mListView.setAdapter(mCustomAdapter);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
mCustomAdapter.getFilter().filter(arg0);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
}
});
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter implements Filterable{
private ArrayList<Contacts> _Contacts;
private Activity context;
private LayoutInflater inflater;
private ValueFilter valueFilter;
private ArrayList<Contacts> mStringFilterList;
public CustomAdapter(Activity context, ArrayList<Contacts> _Contacts) {
super();
this.context = context;
this._Contacts = _Contacts;
mStringFilterList = _Contacts;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}
@Override
public int getCount() {
return _Contacts.size();
}
@Override
public Object getItem(int position) {
return _Contacts.get(position).getName();
}
@Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView tname, tplace;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.activity_main, null);
holder.tname = (TextView) convertView.findViewById(R.id.textView1);
holder.tplace = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.tname.setText("" + _Contacts.get(position).getName());
holder.tplace.setText("" + "" + _Contacts.get(position).getId());
return convertView;
}
@Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint!=null && constraint.length()>0){
ArrayList<Contacts> filterList=new ArrayList<Contacts>();
for(int i=0;i<mStringFilterList.size();i++){
if((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Contacts contacts = new Contacts();
contacts.setName(mStringFilterList.get(i).getName());
contacts.setId(mStringFilterList.get(i).getId());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=mStringFilterList.size();
results.values=mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
_Contacts=(ArrayList<Contacts>) results.values;
notifyDataSetChanged();
}
}
}
Contacts.java
public class Contacts {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_marginTop="2dp"
android:background="@android:color/black"
android:gravity="center_vertical"
android:paddingBottom="2dp"
android:paddingTop="2dp"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@android:color/white" />
This is a sample project code. Use this code this will really help you
Filtering a ListView with Baseadapter filters text not images
First refactor your code. Create a class that holds name, picture and other friend data together.
class Friend {
public String name;
public String picture;
... /* more members and access methods*/
};
Then modify your adapter and filtering code accordingly.
FilterResults
should contain theArrayList<Friend>
, i.e. a list ofFriend
objects and not just the names.In Adapter, replace
List<String> arrayListNames;
List<String> arrayPictures;
with
List<Friend> friendsList;
Change the
getView
method to access data from thefriendsList
object list.
After these changes the code will look better and work better.
Update:
Make sure your adapter's getItem
method returns a Friend
object
public Object getItem(int position) {
return mFriendsList.get(position);
}
Filtering ListView extending BaseAdapter
Use two arraylist one for original data and other is filtering.
update your adapter constructor .
private ArrayList<Names> originalData = null;
private ArrayList<Names> filteredData = null;
public adapter(Activity c, ArrayList<Names> list) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.filteredData = list;
this.originalData = list;
mContext = c;
}
@Override
public int getCount() {
return filteredData.size();
}
@Override
public Object getItem(int position) {
return filteredData.get(position);
}
On Filter
@Override
public Filter getFilter() {
if (filter == null) filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String constraintStr = constraint.toString().toLowerCase(Locale.getDefault());
FilterResults result = new FilterResults();
if (constraintStr != null & constraintStr.length() > 0) {
ArrayList<Names> filterItems = new ArrayList<Names>();
synchronized (this) {
for (ContactInfo item : originalData) {
if (item.name.toLowerCase(Locale.getDefault()).startsWith(constraintStr)) {
filterItems.add(item);
}
}
result.count = filterItems.size();
result.values = filterItems;
}
} else {
synchronized (this) {
result.count = originalData.size();
result.values = originalData;
}
}
return result;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.values != null) {
namelist = (List<Names>) results.values;
notifyDataSetChanged();
}
}
};
return filter;
}
Filter ListView from custom base adapter
Change your adapter class like this
public class ChartListAdapter extends BaseAdapter implements Filterable {
ArrayList<ChartModel> list;
ArrayList<ChartModel> filteredList;
Context context;
public ChartListAdapter(ArrayList<ChartModel> list, Context context) {
this.list = list;
this.filteredList = list;
this.context = context;
}
@Override
public int getCount() {
if(filteredList != null) {
return filteredList.size();
} else {
return 0;
}
}
@Override
public Object getItem(int i) {
return filteredList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
view = View.inflate(context, R.layout.chart_card, null);
}
TextView chart_name = view.findViewById(R.id.chart_name);
SwitchCompat switchCompat = view.findViewById(R.id.chart_selected);
switchCompat.setTag(filteredList.get(i).getChart_id());
chart_name.setText(filteredList.get(i).getChart_name());
switchCompat.setChecked(filteredList.get(i).getCard_selected());
switchCompat.setOnCheckedChangeListener((compoundButton, b) -> {
String getTag = compoundButton.getTag().toString();
Toast.makeText(context, getTag + " is selected :" + b, Toast.LENGTH_LONG).show();
});
return view;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint == null || constraint.length() == 0){
filteredList = list;
}else{
ArrayList<ChartModel> resultsModel = new ArrayList<>();
String searchStr = constraint.toString().toLowerCase();
for(ChartModel itemsModel:list){
if(itemsModel.getChart_id().contains(searchStr)){
resultsModel.add(itemsModel);
}
filteredList = resultsModel;
}
}
filterResults.values = filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (ArrayList<ChartModel>) results.values;
notifyDataSetChanged();
}
};
}
}
Related Topics
Why Does It Take So Long for Android's Mediaplayer to Prepare Some Live Streams for Playback
Android Singleton with Global Context
Android Action Bar Searchview as Autocomplete
How to Install Android Market App on the Emulator
How to Get the Mobile Number of Current Sim Card in Real Device
Android Studio Getslotfrombufferlocked: Unknown Buffer Error
Android How to Runonuithread in Other Class
How to Change the Led Intensity of an Android Device
How to Filter Listview Data When Typing on Edittext in Android
How to Set Soap Header Using Ksoap2 - Android
Adding Your Own SQLite Database to an Android Application
How to Add Android Support V7 Libraries in Eclipse
Gmail 5.0 App Fails with "Permission Denied for the Attachment" When It Receives Action_Send Intent
Parse JSON Array Response Using Retrofit & Gson
Can the Android Emulator Record and Play Back Audio Using Pc Hardware