Kindly help me in my code, It doesn't search perfect all other values remain on their position except the search able string.
Here is the code of filterable class
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Interpolator.Result;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class ListViewAdapter_claimlist extends BaseAdapter implements Filterable{
Activity context;
String claimid[];
String ref[];
String policy[];
String natureofloss[];
String registration[];
String status[];
private ItemFilter mFilter = new ItemFilter();
private List<String>originalData = null;
private List<String>filteredData = null;
private List<String>claimidFilter = null;
private List<String>refFilter = null;
private List<String>nautreoflossfilter = null;
private List<String>registrationFilter = null;
private List<String>statusFilter = null;
ArrayList<abc> alldata = new ArrayList<abc>();
public ListViewAdapter_claimlist(Activity context, String[] claimid, String[] ref,String[] policy, String[] natureofloss,String[] registration, String[] status) {
super();
this.context = context;
this.claimid = claimid;
this.ref = ref;
this.policy = policy;
this.natureofloss = natureofloss;
this.registration = registration;
this.status = status;
this.filteredData = new ArrayList<String>(Arrays.asList(this.policy));
this.originalData = new ArrayList<String>(Arrays.asList(this.policy));
this.claimidFilter = new ArrayList<String>(Arrays.asList(this.claimid));
this.refFilter = new ArrayList<String>(Arrays.asList(this.ref));
this.nautreoflossfilter = new ArrayList<String>(Arrays.asList(this.natureofloss));
this.registrationFilter = new ArrayList<String>(Arrays.asList(this.registration));
this.statusFilter = new ArrayList<String>(Arrays.asList(this.status));
for(int i = 0; i<this.claimid.length; i++)
{
abc a = new abc();
a.setClaimid(claimid[i]);
a.setRef(ref[i]);
a.setPolicy(policy[i]);
a.setNatureofLoss(natureofloss[i]);
a.setRegistration(registration[i]);
a.setStatus(status[i]);
alldata.add(a);
}
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView cliamid;
TextView ref;
TextView policy;
TextView natureofloss;
TextView registration;
TextView status;
}
public View getView(int position, View convertView, final ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rowitem_cliamlist, null);
holder = new ViewHolder();
holder.cliamid = (TextView) convertView.findViewById(R.id.tv_claims);
holder.ref = (TextView) convertView.findViewById(R.id.tv_referencepolicy);
holder.policy = (TextView) convertView.findViewById(R.id.tv_policyNo);
holder.natureofloss = (TextView) convertView.findViewById(R.id.tv_natureoflos);
holder.registration = (TextView) convertView.findViewById(R.id.tv_registration);
holder.status = (TextView) convertView.findViewById(R.id.tv_claimstatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
abc aa = alldata.get(position);
holder.cliamid.setText(aa.getClaimid());
holder.ref.setText(aa.getRef());
holder.policy.setText(filteredData.get(position));
holder.natureofloss.setText(aa.getNatureofloss());
holder.registration.setText(aa.getRegistration());
holder.status.setText(aa.getStatus());
return convertView;
}
//--------------------------------------------------------------------------------
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public class abc
{
String claimid;
String ref;
String policy;
String natureofloss;
String registration;
String status;
public void setClaimid(String claimid)
{
this.claimid = claimid;
}
public void setRef(String ref)
{
this.ref = ref;
}
public void setPolicy(String policy)
{
this.policy = policy;
}
public void setNatureofLoss(String natureofloss)
{
this.natureofloss = natureofloss;
}
public void setRegistration(String registration)
{
this.registration = registration;
}
public void setStatus(String status)
{
this.status = status;
}
public String getClaimid()
{
String claimid = this.claimid;
return claimid;
}
public String getRef()
{
String ref = this.ref;
return ref;
}
public String getPolicy()
{
String Policy = this.policy;
return Policy;
}
public String getNatureofloss()
{
String Natureofloss = this.natureofloss;
return Natureofloss;
}
public String getRegistration()
{
String Registration = this.registration;
return Registration;
}
public String getStatus()
{
String Status = this.status;
return Status;
}
}
}
Edit Text Event Handler
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Before Search
When Search by Police No(policy# in code)
Thank in Advance :)
You can choose another trick for this, set an textWatcher on the edit text where you are entering the search text.
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
String text = searchText.getText().toString()
.toLowerCase(Locale.getDefault());
lviewAdapter.filter(text);
}
});
put a filter method in Adapter class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
temp.clear();
if (charText.length() == 0) {
temp.addAll(list_original);
} else {
for (Abc abc: list_original) {
// if you want to search via policy
if (abc.getPolicy().toLowerCase(Locale.getDefault())
.contains(charText)) {
temp.add(abc);
}
}
}
notifyDataSetChanged();
}
And create two Abc type arraylists one is temp and one is original, always pass data to the listview in getview method from temp list, so that you can make changes in temp, not the original one. In above case the temp list cleared first and run a loop to check that search text in original list if matches then add that object to temp list, and called notifyDataSetChanged.. Voila
Related
I am trying since last some days but I didn't achieve my goal. The problem I am facing in my code is when I type in EditText for search in list view as the searching criteria depend on 'Policy No'. It works perfect for single value (Policy No) and it changes as I type. But the remaining other values doesn't changes it remains on their own places. Kindly Help me for this. Thanks In Advance . and sorry for my bad English.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Interpolator.Result;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class ListViewAdapter_claimlist extends BaseAdapter implements Filterable{
Activity context;
String claimid[];
String ref[];
String policy[];
String natureofloss[];
String status[];
private ItemFilter mFilter = new ItemFilter();
private List<String>originalData = null;
private List<String>filteredData = null;
private List<String>claimidFilter = null;
private List<String>refFilter = null;
private List<String>nautreoflossfilter = null;
private List<String>statusFilter = null;
ArrayList<abc> alldata = new ArrayList<abc>();
public ListViewAdapter_claimlist(Activity context, String[] claimid, String[] ref,String[] policy, String[] natureofloss, String[] status) {
super();
this.context = context;
this.claimid = claimid;
this.ref = ref;
this.policy = policy;
this.natureofloss = natureofloss;
this.status = status;
this.filteredData = new ArrayList<String>(Arrays.asList(this.policy));
this.originalData = new ArrayList<String>(Arrays.asList(this.policy));
this.claimidFilter = new ArrayList<String>(Arrays.asList(this.claimid));
this.refFilter = new ArrayList<String>(Arrays.asList(this.ref));
this.nautreoflossfilter = new ArrayList<String>(Arrays.asList(this.natureofloss));
this.statusFilter = new ArrayList<String>(Arrays.asList(this.status));
for(int i = 0; i<this.claimid.length; i++)
{
abc a = new abc();
a.setClaimid(claimid[i]);
a.setRef(ref[i]);
a.setPolicy(policy[i]);
a.setNatureofLoss(natureofloss[i]);
a.setStatus(status[i]);
alldata.add(a);
}
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView cliamid;
TextView ref;
TextView policy;
TextView natureofloss;
TextView status;
}
public View getView(int position, View convertView, final ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rowitem_cliamlist, null);
holder = new ViewHolder();
holder.cliamid = (TextView) convertView.findViewById(R.id.tv_claims);
holder.ref = (TextView) convertView.findViewById(R.id.tv_referencepolicy);
holder.policy = (TextView) convertView.findViewById(R.id.tv_policyNo);
holder.natureofloss = (TextView) convertView.findViewById(R.id.tv_natureoflos);
holder.status = (TextView) convertView.findViewById(R.id.tv_claimstatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Button b = (Button) convertView.findViewById(R.id.btn_quotaions_claims);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(), QuotationList.class);
intent.putExtra("quot_id", holder.cliamid.getText().toString());
Constants.claim_id = holder.cliamid.getText().toString();
context.startActivity(intent);
}
});
Button c = (Button) convertView.findViewById(R.id.btn_claimdetail_claims);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringTokenizer tokens = new StringTokenizer(holder.ref.getText().toString(), "/");
String first = tokens.nextToken();
String two = tokens.nextToken();
Intent intent = new Intent(parent.getContext(), Claimform.class);
intent.putExtra("ref_id", first);
intent.putExtra("typeofintimation", holder.natureofloss.getText().toString());
Constants.key_id = first;
context.startActivity(intent);
}
});
abc aa = alldata.get(position);
holder.cliamid.setText(aa.getClaimid());
holder.ref.setText(aa.getRef());
holder.policy.setText(filteredData.get(position));
holder.natureofloss.setText(aa.getNatureofloss());
holder.status.setText(aa.getStatus());
return convertView;
}
//--------------------------------------------------------------------------------
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public class abc
{
String claimid;
String ref;
String policy;
String natureofloss;
String status;
public void setClaimid(String claimid)
{
this.claimid = claimid;
}
public void setRef(String ref)
{
this.ref = ref;
}
public void setPolicy(String policy)
{
this.policy = policy;
}
public void setNatureofLoss(String natureofloss)
{
this.natureofloss = natureofloss;
}
public void setStatus(String status)
{
this.status = status;
}
public String getClaimid()
{
String claimid = this.claimid;
return claimid;
}
public String getRef()
{
String ref = this.ref;
return ref;
}
public String getPolicy()
{
String Policy = this.policy;
return Policy;
}
public String getNatureofloss()
{
String Natureofloss = this.natureofloss;
return Natureofloss;
}
public String getStatus()
{
String Status = this.status;
return Status;
}
}
}
EditText Event
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Use these following lines of code...It can be helpful for you
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(searchText.getText().toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Please am trying to implement a filter on my listview. But whenever the text change, the list disappears.Please Help
Here are my code. The adapter class.
package com.talagbe.schymn;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class HymnsAdapter extends ArrayAdapter<Hymns> {
ArrayList<Hymns> hymnarray;
Context context;
LayoutInflater inflater;
int Resource;
public HymnsAdapter(Context context, int resource, ArrayList<Hymns> objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
hymnarray=objects;
Resource= resource;
this.context=context;
inflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null){
convertView= inflater.inflate(Resource,null);
holder= new ViewHolder();
holder.hymntitle= (TextView) convertView.findViewById(R.id.Hymn_title);
// holder.hymntext= (TextView) convertView.findViewById(R.id.Channel_name);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
holder.hymntitle.setText(hymnarray.get(position).getTitle());
//holder.hymntext.setText(hymnarray.get(position).getText());
return convertView;
}
static class ViewHolder{
public TextView hymntitle;
public TextView hymntext;
}
}
Here is the other class where am trying to implement the filter. I have an edittext,where i implement on textChangeListener
package com.talagbe.schymn;
import java.util.ArrayList;
import database.DatabaseHelper;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView.OnItemClickListener;
public class Home extends Fragment {
private static final String DB_NAME = "schymn.sqlite";
private static final String TABLE_NAME = "Hymns";
private static final String Hymn_ID = "_id";
private static final String Hymn_Title = "Title";
private static final String Hymn_Text = "Text";
private SQLiteDatabase database;
ListView list;
EditText search;
HymnsAdapter vadapter;
ArrayList<Hymns> HymnsList;
String url;
Context context=null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.index, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView)getActivity().findViewById(R.id.hymn_list);
search = (EditText) getActivity().findViewById(R.id.search);
HymnsList = new ArrayList<Hymns>();
DatabaseHelper dbOpenHelper = new DatabaseHelper(getActivity(), DB_NAME);
database = dbOpenHelper.openDataBase();
fillHymns();
//setUpList();
}
private void fillHymns() {
Cursor hymnCursor = database.query(TABLE_NAME,
new String[]
{Hymn_ID, Hymn_Title,Hymn_Text},
null, null, null, null
, Hymn_Title);
hymnCursor.moveToFirst();
if(!hymnCursor.isAfterLast()) {
do {
Hymns hy = new Hymns();
hy.setTitle(hymnCursor.getString(1));
hy.setText(hymnCursor.getString(2));
HymnsList.add(hy);
} while (hymnCursor.moveToNext());
}
hymnCursor.close();
vadapter = new HymnsAdapter(getActivity().getApplicationContext(),R.layout.hymns,HymnsList);
list.setAdapter(vadapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity().getApplicationContext(), Hymn_Text.class);
intent.putExtra("Title",HymnsList.get(position).getTitle());
intent.putExtra("Text",HymnsList.get(position).getText());
startActivity(intent);
//Log.i("Text",HymnsList.get(position).getText());
}
});
search.addTextChangedListener( new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
// TODO Auto-generated method stub
if(count>0){
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Home.this.vadapter.getFilter().filter(s);
Log.i("Changed",s.toString());
}
});
}
}
The log,logs whatever input i type in,but doesn't show the listview. Thank you
You can use the Filterable interface on your Adapter, have a look at the example below:
public class SearchableAdapter extends BaseAdapter implements Filterable {
private List<String>originalData = null;
private List<String>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<String> data) {
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.list_view);
// Bind the data efficiently with the holder.
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// If weren't re-ordering this you could rely on what you set last time
holder.text.setText(filteredData.get(position));
return convertView;
}
static class ViewHolder {
TextView text;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
In your Activity or Fragment where of Adapter is instantiated :
editTxt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
mSearchableAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Here are the links for the original source and another example
I hope it will be helpful for others.
// put below code (method) in Adapter class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
myList.clear();
if (charText.length() == 0) {
myList.addAll(arraylist);
}
else
{
for (MyBean wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
myList.add(wp);
}
}
}
notifyDataSetChanged();
}
declare below code in adapter class
private ArrayList<MyBean> myList; // for loading main list
private ArrayList<MyBean> arraylist=null; // for loading filter data
below code in adapter Constructor
this.arraylist = new ArrayList<MyBean>();
this.arraylist.addAll(myList);
and below code in your activity class
final EditText searchET = (EditText)findViewById(R.id.search_et);
// Capture Text in EditText
searchET.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
In your CustomAdapter class implement filterable.
public class CustomAdapter extends BaseAdapter implements Filterable {
private List<ItemsModel> itemsModelsl;
private List<ItemsModel> itemsModelListFiltered;
private Context context;
public CustomAdapter(List<ItemsModel> itemsModelsl, Context context) {
this.itemsModelsl = itemsModelsl;
this.itemsModelListFiltered = itemsModelsl;
this.context = context;
}
#Override
public int getCount() {
return itemsModelListFiltered.size();
}
#Override
public Object getItem(int position) {
return itemsModelListFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.row_items,null);
TextView names = view.findViewById(R.id.name);
TextView emails = view.findViewById(R.id.email);
ImageView imageView = view.findViewById(R.id.images);
names.setText(itemsModelListFiltered.get(position).getName());
emails.setText(itemsModelListFiltered.get(position).getEmail());
imageView.setImageResource(itemsModelListFiltered.get(position).getImages());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("main activity","item clicked");
startActivity(new Intent(MainActivity.this,ItemsPreviewActivity.class).putExtra("items",itemsModelListFiltered.get(position)));
}
});
return view;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint == null || constraint.length() == 0){
filterResults.count = itemsModelsl.size();
filterResults.values = itemsModelsl;
}else{
List<ItemsModel> resultsModel = new ArrayList<>();
String searchStr = constraint.toString().toLowerCase();
for(ItemsModel itemsModel:itemsModelsl){
if(itemsModel.getName().contains(searchStr) || itemsModel.getEmail().contains(searchStr)){
resultsModel.add(itemsModel);
}
filterResults.count = resultsModel.size();
filterResults.values = resultsModel;
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
itemsModelListFiltered = (List<ItemsModel>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
}
You can get the whole tutorial here:
ListView With Search/Filter and OnItemClickListener
Github Source Code
please check below code it will help you
DrawerActivity.userListview
.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int pos = position;
Intent intent = new Intent(getContext(),
UserDetail.class);
intent.putExtra("model", list.get(position));
context.startActivity(intent);
}
});
return convertView;
}
#Override
public android.widget.Filter getFilter() {
return new android.widget.Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
getContext(), getCount(), updatelist);
if (results.equals(constraint)) {
updatelist.add(modelobj);
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
list = new ArrayList<UserListModel>();
if (constraint != null && DrawerActivity.userlist != null) {
constraint = constraint.toString().toLowerCase();
int length = DrawerActivity.userlist.size();
int i = 0;
while (i < length) {
UserListModel modelobj = DrawerActivity.userlist.get(i);
String data = modelobj.getFirstName() + " "
+ modelobj.getLastName();
if (data.toLowerCase().contains(constraint.toString())) {
list.add(modelobj);
}
i++;
}
filterResults.values = list;
filterResults.count = list.size();
}
return filterResults;
}
};
}
#Override
public int getCount() {
return list.size();
}
#Override
public UserListModel getItem(int position) {
return list.get(position);
}
If you want to achieve filtering with custom model class in kotlin then you can implement below code.
Step 1:
Add SearchView in your xml file and then in your activity or fragment implement SearchView.OnQueryTextListener
class SearchActivity : AppCompatActivity(),SearchView.OnQueryTextListener {
lateinit var sectionModelArrayList: ArrayList<CategorySectionModel>
lateinit var filteredArrayList: ArrayList<CategorySectionModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_updated)
searchView.setOnQueryTextListener(this)
}
//Called this method with you own data to populate the recycler view.
private fun parseJson() {
rv_category_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
adapter = CategoryLabelAdapter(sectionModelArrayList, this)
rv_category_list.adapter = adapter
}
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
adapter.filter!!.filter(newText.toString())
return false
}
My model class CategorySectionModel looks like
class CategorySectionModel(val categoryLabel: String, val categoryItemList: ArrayList<CategoryItem>)
Now we have to work on adapter class and there you need to implement Filterable interface and override getFilter() method like below
class CategoryLabelAdapter(internal var data: ArrayList<CategorySectionModel>?, internal var activity: Context) : RecyclerView.Adapter<CategoryLabelAdapter.ViewHolder>(), Filterable {
val originalList = data
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_category_name, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return data!!.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
data?.get(position)?.let { holder.bindItem(it) }
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
#SuppressLint("SetTextI18n")
fun bindItem(data: CategorySectionModel) {
itemView.tv_category_name.text = data.categoryLabel
}
}
override fun getFilter(): Filter? {
return object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
val results = FilterResults()
if (constraint.isEmpty()) {
//no filter implemented we return full list
results.values = data
results.count = data!!.size
} else {
//Here we perform filtering operation
val list: ArrayList<CategorySectionModel> = ArrayList()
for (p in data!!) {
if (p.categoryLabel.toUpperCase().startsWith(constraint.toString().toUpperCase())) list.add(p)
}
results.values = list
results.count = list.size
}
return results
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0 || constraint == "") {
data = originalList
notifyDataSetChanged()
} else {
data = results.values as ArrayList<CategorySectionModel>?
notifyDataSetChanged()
}
}
}
}
}
First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup.
Before moving objects to lists first initializes Them the below:
//Declaring
public EditText etPesquisa;
public ContasPagarAdapter adapterNormal;
public List<ContasPagar> lstBkp;
public List<ContasPagar> lstCp;
//Within the onCreate method, type the following:
etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);
etPesquisa.addTextChangedListener(new TextWatcher(){
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
filter(String.valueOf(cs));
}
#Override
public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable e){
}
});
//Before moving objects to lists first initializes them as below:
lstCp = new ArrayList<ContasPagar>();
lstBkp = new ArrayList<ContasPagar>();
//When you add objects to the main list, repeat the procedure also for bkp list, as follows:
lstCp.add(cp);
lstBkp.add(cp);
//Now initializes the adapter and let the listener, as follows:
adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);
lvContasPagar.setAdapter(adapterNormal);
lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));
//Now create the methods inside actito filter the text entered by the user, as follows:
public void filter(String charText){
charText = charText.toLowerCase();
lstCp.clear();
if (charText.length() == 0){
lstCp.addAll(lstBkp);
appendAddItem(lstBkp);
}
else {
for (int i = 0; i < lstBkp.size(); i++){
if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){
lstCp.add(lstBkp.get(i));
}
}
appendAddItem(lstCp);
}
}
private void appendAddItem(final List<ContasPagar> novaLista){
runOnUiThread(new Runnable(){
#Override
public void run(){
adapterNormal.notifyDataSetChanged();
}
});
}
You can implement search filter in listview by two ways. 1. using searchview 2. using edittext.
If yo want to use searchview then read here : searchview filter.
If you want to use edittext, read below.
I have taken reference from : listview search filter android
Code snippets to make filter with edittext.
First create model class MovieNames.java:
public class MovieNames {
private String movieName;
public MovieNames(String movieName) {
this.movieName = movieName;
}
public String getMovieName() {
return this.movieName;
}
}
Create listview_item.xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Make ListViewAdapter.java class :
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private ArrayList<MovieNames> arraylist;
public ListViewAdapter(Context context, ArrayList<MovieNames> arraylist) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = arraylist;
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public MovieNames getItem(int position) {
return arraylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(arraylist.get(position).getMovieName());
return view;
}
}
Prepare activity_main.xml file :
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.parsaniahardik.searchedit.MainActivity"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="enter query"
android:singleLine="true">
<requestFocus/>
</EditText>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:divider="#694fea"
android:dividerHeight="1dp" />
</LinearLayout>
Finally make MainActivity.java class :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText etsearch;
private ListView list;
private ListViewAdapter adapter;
private String[] moviewList;
public static ArrayList<MovieNames> movieNamesArrayList;
public static ArrayList<MovieNames> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Generate sample data
moviewList = new String[]{"Xmen", "Titanic", "Captain America",
"Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book",
"Tarzan","Cars","Shreck"};
list = (ListView) findViewById(R.id.listView);
movieNamesArrayList = new ArrayList<>();
array_sort = new ArrayList<>();
for (int i = 0; i < moviewList.length; i++) {
MovieNames movieNames = new MovieNames(moviewList[i]);
// Binds all strings into an array
movieNamesArrayList.add(movieNames);
array_sort.add(movieNames);
}
adapter = new ListViewAdapter(this,movieNamesArrayList);
list.setAdapter(adapter);
etsearch = (EditText) findViewById(R.id.editText);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, array_sort.get(position).getMovieName(), Toast.LENGTH_SHORT).show();
}
});
etsearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength = etsearch.getText().length();
array_sort.clear();
for (int i = 0; i < movieNamesArrayList.size(); i++) {
if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) {
Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim());
if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains(
etsearch.getText().toString().toLowerCase().trim())) {
array_sort.add(movieNamesArrayList.get(i));
}
}
}
adapter = new ListViewAdapter(MainActivity.this, array_sort);
list.setAdapter(adapter);
}
});
}
}
you can find custom list adapter class with filterable using text change in edit text...
create custom list adapter class with implementation of Filterable:
private class CustomListAdapter extends BaseAdapter implements Filterable{
private LayoutInflater inflater;
private ViewHolder holder;
private ItemFilter mFilter = new ItemFilter();
public CustomListAdapter(List<YourCustomData> newlist) {
filteredData = newlist;
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = new ViewHolder();
if(inflater==null)
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = inflater.inflate(R.layout.row_listview_item, null);
holder.mTextView = (TextView)convertView.findViewById(R.id.row_listview_member_tv);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.mTextView.setText(""+filteredData.get(position).getYourdata());
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
}
class ViewHolder{
TextView mTextView;
}
private class ItemFilter extends Filter {
#SuppressLint("DefaultLocale")
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<YourCustomData> list = YourObject.getYourDataList();
int count = list.size();
final ArrayList<YourCustomData> nlist = new ArrayList<YourCustomData>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = ""+list.get(i).getYourText();
if (filterableString.toLowerCase().contains(filterString)) {
YourCustomData mYourCustomData = list.get(i);
nlist.add(mYourCustomData);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<YourCustomData>) results.values;
mCustomListAdapter.notifyDataSetChanged();
}
}
mEditTextSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(mCustomListAdapter!=null)
mCustomListAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
One thing I've noticed is that whenever you are editing the list (adding items for example) as well as filtering for it, then inside the #Override getView method, you shouldn't use filteredData.get(position), as it throws an IndexOutOfBounds exception.
Instead, what worked for me, was using the getItem(position) method, which belongs to the ArrayAdapter class.
Just an update.
If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
if(constraint.length() == 0)
{
results.count = originalData.size();
results.values = originalData;
}else {
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
For any query comment below
i want to get the contact numbers in a string when user checked the contact,after which onBackpress the selected values can be stored in database.user can select multiple contacts at a time and when user returns back on the activity,the check box remains checked, so that he can see his selected contacts.
MainActivity
public class MainActivity extends Activity {
String[] cellArray = null;
String contacts;
String phoneNumber, name;
ArrayList<String> phno0 = new ArrayList<String>();
StringBuilder b = new StringBuilder();
//private ArrayAdapter<String> adapter;
List<String> arrayListNames;
private ListView listview;
private EditText edittext;
private List<ProfileBean> list;
private SearchableAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
edittext = (EditText) findViewById(R.id.edittext);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplicationContext(), list);
listview.setAdapter(adapter);
edittext.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
}
#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.getFilter().filter(s.toString());
}
});
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ProfileBean bean = (ProfileBean) arg1.getTag();
Toast.makeText(getApplicationContext(), bean.getName(), Toast.LENGTH_LONG).show();
}
});
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
list.add(new ProfileBean(name, phoneNumber));
}
}
}
Adapterclass
public class SearchableAdapter extends BaseAdapter implements Filterable, OnCheckedChangeListener {
private List<ProfileBean>originalData = null;
private List<ProfileBean>filteredData = null;
private LayoutInflater mInflater;
private ItemFilter mFilter = new ItemFilter();
public SearchableAdapter(Context context, List<ProfileBean> data) {
//mCheckStates = new SparseBooleanArray(filteredData.size());
this.filteredData = data ;
this.originalData = data ;
mInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lname = (TextView) convertView.findViewById(R.id.lname);
holder.no = (CheckBox) convertView.findViewById(R.id.no);
holder.no.setTag(position);
holder.no.setOnCheckedChangeListener(this);
convertView.setTag(R.layout.list_item,holder);
} else {
holder = (ViewHolder) convertView.getTag(R.layout.list_item);
}
ProfileBean bean = filteredData.get(position);
holder.name.setText(bean.getName());
holder.lname.setText(bean.getLname());
convertView.setTag(bean);
return convertView;
}
static class ViewHolder {
TextView name;
TextView lname;
CheckBox no;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<ProfileBean> list = originalData;
int count = list.size();
final ArrayList<ProfileBean> nlist = new ArrayList<ProfileBean>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
ProfileBean bean = list.get(i);
filterableString = bean.getName();
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(bean);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
BeanClass
package com.example.mylistviewtest;
public class ProfileBean {
private String name;
private String lname;
private boolean checked = false ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public ProfileBean(String name, String lname) {
super();
this.name = name;
this.lname = lname;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void toggleChecked() {
checked = !checked ;
}
}
public class kuliner extends ListActivity {
private static String url = "http://kulinermalang.zz.mu/kuliner/daftar_kuliner.php";
private static final String no_id = "id";
private static final String gambar = "gambar";
private static final String nama = "nama_toko";
JSONArray menu = null;
ListView list;
ArrayList<HashMap<String, String>> daftar_kuliner = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_listview);
EditText search = (EditText) findViewById(R.id.tfCari);
//ambil();
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
loadingData loading = new loadingData();
loading.execute();
}
//this method for call data to listView
private class loadingData extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(kuliner.this);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if (response.equalsIgnoreCase("Success")) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
String id_nama;
String gambar_toko = null;
String nama_toko;
String image_url;
try {
menu = json.getJSONArray("daftar");
for (int i = 0; i < menu.length(); i++) {
JSONObject ar = menu.getJSONObject(i);
id_nama = ar.getString(no_id);
gambar_toko = ar.getString(gambar);
nama_toko = ar.getString(nama);
HashMap<String, String> map = new HashMap<String, String>();
map.put(no_id, id_nama);
map.put(gambar, gambar_toko);
map.put(nama, nama_toko);
daftar_kuliner.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Dialog.dismiss();
}
}
}
You could probably do something like this
//get your ListView with attached SimpleAdapter
ListAdapter adapter = listView.getAdapter();
for(int i = 0; i < adapter.getCount(); i++) {
String value = ((HashMap<String, String>)adapter.getItem(i)).get("Your_key");
}
But i'm not sure i understand the question correctly, what is it that you want to accomplish exactly? I'm sorry for asking a question here but i'm not allowed to comment yet :/
in the onTextChangedMethod of TextWatcher, write an if condition that - the edittext values is in the list you are inflating in your listview, if yes them add that edittext value to another list and set that list to your adapter. For Example Here is my Code :- ( Just focus on ListView, ArrayList and TextWatcher. Dont mind other code)
package com.example.alaramsms;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactActivity extends Activity implements OnItemClickListener{
String textlength;
ArrayList<String> filtered_name;
ArrayList<String> filtered_phone;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> mOriginalValues;
MyAdapter mAdapter ;
Button send,btnselect;
ListView lv;
EditText myFilter;
boolean flag = false;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
mAdapter = new MyAdapter(this,name1,phno1);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#SuppressLint("DefaultLocale")
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = myFilter.getText().toString();
filtered_name = new ArrayList<String>();
filtered_phone = new ArrayList<String>();
for (int i = 0; i < name1.size(); i++)
{
if(name1.get(i).toString().toUpperCase().contains(myFilter.getText().toString().toUpperCase()))
{
System.err.println("Selection: " + textlength);
filtered_name.add(name1.get(i));
filtered_phone.add(phno1.get(i));
}
}
mAdapter = new MyAdapter(ContactActivity.this,filtered_name,filtered_phone);
lv.setAdapter(mAdapter); // Here inflating two other lists containing he searched items
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+mAdapter.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(mAdapter.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mAdapter.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
private SparseBooleanArray mCheckStates;
ArrayList<String> name1;
ArrayList<String> phno1;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter(ContactActivity contactActivity, ArrayList<String> name1, ArrayList<String> phno1)
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.name1 = name1;
this.phno1 = phno1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(flag); // You just have to add this line
cb.setOnCheckedChangeListener(this);
return vi;
}
/*
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
//ArrayList<String> name1 = new ArrayList<String>();
arrayList = (ArrayList<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(name1); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
/* if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String name1 = mOriginalValues.get(i).toString();
if (name1.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(name1);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}*/
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
i have a listview and EditText field and i wanna implement search, but my listview is a custom listview populated with array of objects of class Item. And when i press key whole listview gone so i guess the problem is that it cannot match char with object of class Item that's why there is no results when i press a key.
this is my code
filterText = (EditText) findViewById(R.id.editTextfilter);
filterText.addTextChangedListener(filterTextWatcher);
m_items = new ArrayList<Item>();
phoneList=(ListView)findViewById(android.R.id.list);
phoneList.setTextFilterEnabled(true);
this.m_adapter = new ItemAdapter(this,R.layout.row,m_items);
phoneList.setAdapter(this.m_adapter);
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
m_adapter.getFilter().filter(s.toString());
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
any help how to get it works
I had a similar requirement. I have used a custom Filter.
ArrayList<PostData> mPostingData = null;//arraylist of class items
ArrayList<PostData> mTemp = new ArrayList<PostData>();//temporary arraylist of class items
ArrayList<PostData> mOri = new ArrayList<PostData>();//Original arraylist
getListView().setTextFilterEnabled(true);
search= (EditText) findViewById(R.id.searchbox);
search.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCustomListView.getFilter().filter(s);
mCustomListView.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
POJO Class
class PostData {
String mID;
String mPostedBy;
String mTitle;
String mMessage;
String mImageUrl;
String mVideoUrl;
String mType ;
boolean me=false;
}
Custom List View with Filter method overriden. Search based on mTitle of POJO Class
class CustomListView extends ArrayAdapter {
Context context;
LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
PostData mp ;
public CustomListView(Context c)
{
super(c, 0);
mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mIcon1 = BitmapFactory.decodeResource(c.getResources(), R.drawable.text_icon);
mIcon2 = BitmapFactory.decodeResource(c.getResources(), R.drawable.image_icon);
mIcon3 = BitmapFactory.decodeResource(c.getResources(), R.drawable.video_icon);
}
public int getCount() {
if(mPostingData!=null){
return mPostingData.size();
}else{
return 0;
}
}
public void setData(ArrayList<PostData> mPpst) {
mPostingData = mPpst;//contains class items data.
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count >= 0) {
setData((ArrayList<PostData>) results.values);//if results of search is null set the searched results data
} else {
setData(mOri);// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString().toLowerCase();
ArrayList<PostData> foundItems = new ArrayList<PostData>();
if(mTemp!=null)
{
for(int i=0;i<mTemp.size();i++)
{
//If mTitle contains the string entered in Editext
if (mTemp.get(i).mTitle.toString().contains(constraint)) {
foundItems.add(mTemp.get(i));
}
else
{
}
}
}
result.count = foundItems.size();//search results found return count
result.values = foundItems;// return values
}
else
{
result.count=-1;// no search results found
}
return result;
}
};
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
///int type = getItemViewType(arg0);
Log.i("Aru","get View");
if(mPostingData == null ){
return null;
}
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listviewimg, null);
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.ll=(LinearLayout) convertView.findViewById(R.id.lvid);
holder.text = (TextView) convertView.findViewById(R.id.texttitle);
holder.text2 = (TextView) convertView.findViewById(R.id.tvst);
holder.icon = (ImageView) convertView.findViewById(R.id.llimage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
mp = mPostingData.get(position);
String title = mp.mType;
if(mp.mTitle!=null && Name.equals(mp.mPostedBy )){
title = mp.mTitle+" "+title;
//holder.text.setBackgroundColor(Color.WHITE);
holder.ll.setBackgroundResource(R.drawable.listbkgme);
holder.text.setText(title);
}
else if(mp.mTitle!=null && Name!=mp.mPostedBy)
{
title = mp.mTitle+" "+title;
holder.text.setText(title);
}
if(mp.mMessage!=null && Name.equals(mp.mPostedBy )){
holder.ll.setBackgroundResource(R.drawable.listbkgme);
holder.text2.setText(mp.mMessage);
}
else if(mp.mMessage!=null && Name!=(mp.mPostedBy))
{
holder.text2.setText(mp.mMessage);
}
if(mp.mImageUrl!=null ){
holder.icon.setImageBitmap(mIcon2);
}else if(mp.mVideoUrl!=null){
holder.icon.setImageBitmap(mIcon3);
}else{
holder.icon.setImageBitmap(mIcon1);
}
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
ImageView icon;
LinearLayout ll;
}
public long getItemId(int position) {
return position;
}
}
Modify the above according to your requirements. I have tested the code and it works.
Make a data class like this
package ali.search;
public class Data {
public Data() {
}
int id;
private String JobTitle;
private String Department;
private String Locationn;
private String JobRole;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getJobTitle() {
return JobTitle;
}
public void setJobTitle(String jobTitle) {
JobTitle = jobTitle;
}
public String getDepartment() {
return Department;
}
public void setDepartment(String department) {
Department = department;
}
public String getLocation() {
return Locationn;
}
public void setLocation(String location) {
Locationn = location;
}
public String getJobRole() {
return JobRole;
}
public void setJobRole(String jobRole) {
JobRole = jobRole;
}
}
Make Activity class like this
package ali.search;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class SearchActivity extends Activity {
String[] jobtitles = { "Android Developer", "Tester","iOS Developer",
};
String[] departments = { "android", "testing", "iphone" };
String[] locations = { "Delhi", "Mumbai", "Noida" };
String[] jobRoles = { "develop android based apps", "test mobile apps",
"develop iphone based apps" };
private ListView listViewSearch;
private EditText editSearchView;
private SearchAdapter adapter;
private ArrayList<Data> sortedItems = new ArrayList<Data>();
private ArrayList<Data> OrignalItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listViewSearch = (ListView) findViewById(R.id.lvSearch);
editSearchView = (EditText) findViewById(R.id.edittext);
OrignalItems = getListOfType();
sortedItems.addAll(OrignalItems);
adapter = new SearchAdapter(SearchActivity.this, sortedItems);
listViewSearch.setAdapter(adapter);
editSearchView.addTextChangedListener(searchTxtChangeListener);
}
private ArrayList<Data> getListOfType() {
ArrayList<Data> dataList = new ArrayList<Data>();
for (int i = 0; i < 3; i++) {
Data data = new Data();
data.setJobTitle(jobtitles[i]);
data.setDepartment(departments[i]);
data.setLocation(locations[i]);
data.setJobRole(jobRoles[i]);
data.setId(i);
dataList.add(data);
dataList.add(data);// dulicate entry
}
return dataList;
}
private TextWatcher searchTxtChangeListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int textlength = editSearchView.getText().length();
sortedItems.clear();
for (int i = 0; i < OrignalItems.size(); i++) {
if (textlength <= OrignalItems.get(i).getJobTitle().length()) {
if (editSearchView
.getText()
.toString()
.equalsIgnoreCase(
(String) OrignalItems.get(i).getJobTitle().subSequence(0,
textlength))) {
sortedItems.add(OrignalItems.get(i));
}
}
}
adapter.notifyDataSetChanged();
}
};
}
Finally this the custom adapter
package ali.search;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class SearchAdapter extends BaseAdapter{
Context context;
ArrayList<Data> list;
LayoutParams params;
private static LayoutInflater inflater = null;
public SearchAdapter(Context context, ArrayList<Data> list) {
this.context = context;
this.list = list;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (vi == null) {
vi = inflater.inflate(R.layout.search_list_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
holder.txtDepartment = (TextView) vi.findViewById(R.id.txtDepartment);
holder.txtLocation = (TextView) vi.findViewById(R.id.txtLocation);
holder.txtJobRole = (TextView) vi.findViewById(R.id.txtJobRole);
holder.layoutRelative = (RelativeLayout) vi.findViewById(R.id.layoutRelative);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txtTitle.setText(list.get(position).getJobTitle());
holder.txtDepartment.setText(list.get(position).getDepartment());
holder.txtLocation.setText(list.get(position).getLocation());
holder.txtJobRole.setText(list.get(position).getJobRole());
return vi;
}
class ViewHolder {
RelativeLayout layoutRelative;
TextView txtTitle;
TextView txtDepartment;
TextView txtLocation;
TextView txtJobRole;
}
}
It is working fine.
In custom listview,you must create a Filter method in Adapter.