I need to do a search on the data in a list, make a filter. I bought some means of doing this in what seems to me simpler to implement Filtravel in adapting and instantiating their methods, but msm following the whole explanation here did not work. Someone seemed to help me and explain how to make this filter in my project ??? Thanks in advance!
Adapter
public class AdapterBDLocal extends BaseAdapter implements Filterable{
private Context mContext;
private CustomFilter filter;
private List<ProdutosPesquisa> produtosList = new ArrayList<>();
private List<ProdutosPesquisa> filterList = new ArrayList<>();
public AdapterBDLocal(Context mContext, List<ProdutosPesquisa> produtosList) {
this.mContext = mContext;
this.produtosList = produtosList;
}
#Override
public int getCount() {
return produtosList.size();
}
#Override
public Object getItem(int i) {
return produtosList.size();
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View listItem = view;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.item_lista_pesquisa,viewGroup,false);
final ProdutosPesquisa p = produtosList.get(i);
TextView nome = (TextView) listItem.findViewById(R.id.txt_nome_produto2);
nome.setText(p.getNome_completo());
TextView categoria = (TextView) listItem.findViewById(R.id.txt_categoria2);
categoria.setText(p.getCategoria());
TextView unidade = (TextView) listItem.findViewById(R.id.txt_unidade2);
unidade.setText(p.getUnidade());
Button btn_add = (Button)listItem.findViewById(R.id.btn_add);
Button btn_rem = (Button)listItem.findViewById(R.id.btn_rem);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
if(list.size()<=9){
list.add(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Adiconado", Toast.LENGTH_SHORT).show();
if(txt.getText()!= null){
}
} else{
Toast.makeText(mContext, "Sua Lista esta grande demais!", Toast.LENGTH_SHORT).show();
}
}
});
btn_rem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m = p.getCodigo_barras();
list.remove(m);
txt.setText(list.toString());
Toast.makeText(mContext, "Removido da lista!", Toast.LENGTH_SHORT).show();
}
});
return listItem;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
if(filter == null)
{
filter=new CustomFilter();
}
return filter;
}
//INNER CLASS
class CustomFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults results=new FilterResults();
if(constraint != null && constraint.length()>0)
{
//CONSTARINT TO UPPER
constraint=constraint.toString().toUpperCase();
ArrayList<ProdutosPesquisa> filters=new ArrayList<ProdutosPesquisa>();
//get specific items
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getNome_completo().toUpperCase().contains(constraint))
{
ProdutosPesquisa p = new ProdutosPesquisa();
p.setNome_completo(filterList.get(i).getNome_completo());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
produtosList = (ArrayList<ProdutosPesquisa>) results.values;
notifyDataSetChanged();
}
}
}
Activity
public class PesquisaTesteActivity extends AppCompatActivity {
public static TextView txt;
List<ProdutosPesquisa> lista_produtos;
ListView lv;
AdapterBDLocal adapter;
public static ArrayList list = new ArrayList();
private SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pesquisa_teste);
lv = (ListView)findViewById(R.id.lv2);
searchView = (SearchView) findViewById(R.id.search);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
lista_produtos = DataBaseClass.getInstance(getApplicationContext()).getAllProdutos();
txt = findViewById(R.id.textView);
adapter = new AdapterBDLocal(PesquisaTesteActivity.this, lista_produtos);
lv.setAdapter(adapter);
}
}
Here is my adapter class, very simple to use just modify it according to your needs:
public class DriverListAdapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
private List<DriverList> driverLists = null;
private ArrayList<DriverList> arrayListDriverLists = null;
AppCompatActivity act;
public DriverListAdapter(Context context,
List<DriverList> driverLists) {
mContext = context;
this.driverLists = driverLists;
arrayListDriverLists = new ArrayList<>(driverLists);
inflater = LayoutInflater.from(mContext);
act = (AppCompatActivity) context;
}
public class ViewHolder {
TextView driverNameTv, carNameTv;
}
#Override
public int getCount() {
return driverLists.size();
}
#Override
public DriverList getItem(int position) {
return driverLists.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.lv_items_driver_list, null);
holder.driverNameTv = view.findViewById(R.id.lv_items_drivers_name_tv);
holder.carNameTv = view.findViewById(R.id.lv_items_drivers_car_tv);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.driverNameTv.setText(driverLists.get(position).getDriverName());
holder.carNameTv.setText(driverLists.get(position).getDriverCar());
return view;
}
/**
* Filter Class for item searching
*
* #param charText Text to be searched
*/
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverLists.clear();
if (charText.length() == 0) {
driverLists.addAll(arrayListDriverLists);
} else {
for (DriverList driverList : arrayListDriverLists) {
if (driverList.getDriverName().toLowerCase(Locale.getDefault()) // driverList.getDriverName() will let the user to search driver's name
.contains(charText)) {
driverLists.add(driverList);
}
}
}
notifyDataSetChanged();
}
}
Here is my pojo class:
public class DriverList {
String driverName, driverEmailId, driverCar, timestamp;
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getDriverEmailId() {
return driverEmailId;
}
public void setDriverEmailId(String driverEmailId) {
this.driverEmailId = driverEmailId;
}
public String getDriverCar() {
return driverCar;
}
public void setDriverCar(String driverCar) {
this.driverCar = driverCar;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
Here is activity code for the editText where you will perform search:
final EditText driverSearchEt = dialog.findViewById(R.id.custom_dialog_select_car_search_et);
driverSearchEt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (driverSearchEt.getText().toString().length() == 0) {
if (carsListAdapter != null) {
carsListAdapter.filter("");
}
} else {
String text = driverSearchEt.getText().toString().toLowerCase(Locale.getDefault());
if (carsListAdapter != null) {
carsListAdapter.filter(text);
}
}
}
});
And don't forget to initialize your listview and adapter. Hope it helps as it is working for me.
Related
I am configuring a resource in my app to search in a Listview using a custom Adapter. I using an EditText to type the string and passing the text to Adapter on addTextChangedListener Event, but it is not working.
I configure the adapter with "implements Filterable" and enable Listview with ".setTextFilterEnabled(true)", but doesn´t work.
I saw that I must implement "public Filter getFilter()" but I have no idea how can I do that.
When I type some words in EditText, like "cel" or "12" the filter goes in action, but the result is always the same: The first two items in Listview, no matter what is into the Listview (the content of listview is random).
Below a snippet of my Fragment Activity:
public class VideosFragment extends Fragment {
private ListView listView;
private ArrayList<String> idVideo = new ArrayList<>();
private ArrayList<String> titleVideo = new ArrayList<>();
private ArrayList<String> descVideo = new ArrayList<>();
private ArrayList<String> urlVideo = new ArrayList<>();
private ArrayList<String> channelTitle = new ArrayList<>();
private ArrayList<String> canalTitle = new ArrayList<>();
private ArrayList<String> canalId = new ArrayList<>();
private CustomFiltraCanaisAdapter customFiltraCanaisAdapter;
private EditText editText;
CustomVideoAdapter customVideoAdapter;
public VideosFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_videos, container, false);
// Configure Listview
listView = (ListView)view.findViewById(R.id.listView_videos);
//Create search parameters
editText = (EditText) view.findViewById(R.id.searchList);
listView.setTextFilterEnabled(true);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String text = editText.getText().toString().toLowerCase(Locale.getDefault());
VideosFragment.this.customVideoAdapter.getFilter().filter(text);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
and below my CustomAdapter:
public class CustomVideoAdapter extends ArrayAdapter<String> implements Filterable {
private final Activity context;
private final ArrayList<String> videoTitle;
private final ArrayList<String> videoDesc;
private final ArrayList<String> videoId;
private final ArrayList<String> channelTitle;
private final ArrayList<String> imgurl;
public CustomVideoAdapter(Activity context, ArrayList<String> videoTitle,
ArrayList<String> videoId,
ArrayList<String> channelTitle,
ArrayList<String> imgurl,
ArrayList<String> videoDesc) {
super(context, R.layout.custom_lista_videos, videoTitle);
// TODO Auto-generated constructor stub
this.context = context;
this.videoTitle = videoTitle;
this.videoDesc = videoDesc;
this.videoId = videoId;
this.channelTitle = channelTitle;
this.imgurl = imgurl;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.custom_lista_videos, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtVideoTitle);
ImageView imgPhoto = (ImageView) rowView.findViewById(R.id.imgPhoto);
TextView txtChannelTitle = (TextView) rowView.findViewById(R.id.txtChannelTitle);
TextView txtVideoId = (TextView) rowView.findViewById(R.id.txtVideoId);
TextView txtVideoDesc = (TextView) rowView.findViewById(R.id.txtVideoDesc);
txtTitle.setText(videoTitle.get(position));
Picasso.with(context).load(imgurl.get(position)).into(imgPhoto);
txtChannelTitle.setText(channelTitle.get(position));
txtVideoId.setText(videoId.get(position));
txtVideoDesc.setText(videoDesc.get(position));
return rowView;
};
What is missing?
After some helps I trying to create (and use) a Model Class, but I still have no progress because I did not figure out how can I must change my code on "CustomAdapter" to use correctly this code.
My Model Class is below:
public class FilteredVideoAdapter {
private ArrayList<String> storedVideoTitle = null;
private ArrayList<String> storedVideoDesc = null;
private ArrayList<String> storedVideoId = null;
private ArrayList<String> storedChannelTitle = null;
private ArrayList<String> storedImgurl = null;
public FilteredVideoAdapter(){
}
public ArrayList<String> getStoredVideoTitle() {
return storedVideoTitle;
}
public void setStoredVideoTitle(ArrayList<String> storedVideoTitle) {
this.storedVideoTitle = storedVideoTitle;
}
public ArrayList<String> getStoredVideoDesc() {
return storedVideoDesc;
}
public void setStoredVideoDesc(ArrayList<String> storedVideoDesc) {
this.storedVideoDesc = storedVideoDesc;
}
public ArrayList<String> getStoredVideoId() {
return storedVideoId;
}
public void setStoredVideoId(ArrayList<String> storedVideoId) {
this.storedVideoId = storedVideoId;
}
public ArrayList<String> getStoredChannelTitle() {
return storedChannelTitle;
}
public void setStoredChannelTitle(ArrayList<String> storedChannelTitle) {
this.storedChannelTitle = storedChannelTitle;
}
public ArrayList<String> getStoredImgurl() {
return storedImgurl;
}
public void setStoredImgurl(ArrayList<String> storedImgurl) {
this.storedImgurl = storedImgurl;
}
public FilteredVideoAdapter withFilteredVideoAdapter(
ArrayList<String> storedVideoTitle,
ArrayList<String> storedVideoDesc,
ArrayList<String> storedVideoId,
ArrayList<String> storedChannelTitle,
ArrayList<String> storedImgurl){
this.storedVideoTitle = storedVideoTitle;
this.storedVideoDesc = storedVideoDesc;
this.storedVideoId = storedVideoId;
this.storedChannelTitle = storedChannelTitle;
this.storedImgurl = storedImgurl;
return this;
}
}
This is what you have to do inside your adapter, you might need to do some tweaks:-
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// If the constraint (search string/pattern) is null
// or its length is 0, i.e., its empty then
// we just set the `values` property to the
// original contacts list which contains all of them
if (constraint == null || constraint.length() == 0) {
results.values = videoTitle;;
results.count = videoTitle.size();
}
else {
// Some search copnstraint has been passed
// so let's filter accordingly
ArrayList<String> filteredTitle = new ArrayList<String>();
// We'll go through all the title and see
// if they contain the supplied string
for (String c : string) {
if (string.toUpperCase().contains( constraint.toString().toUpperCase() )) {
// if `contains` == true then add it
// to our filtered list
filteredTitle.add(c);
}
}
// Finally set the filtered values and size/count
results.values = filteredTitle;
results.count = filteredTitle.size();
}
// Return our FilterResults object
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mList = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
};
}
Hope this will help you.
You can do this without using filterable, Try this code
Your Activity Code
vendorSearchEt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (vendorSearchEt.getText().toString().length() == 0) {
if (vendorsListAdapter != null) {
vendorsListAdapter.filter("");
}
} else {
String text = vendorSearchEt.getText().toString().toLowerCase(Locale.getDefault());
if (vendorsListAdapter != null) {
vendorsListAdapter.filter(text);
}
}
}
});
Adapter Class
public class VendorsListAdapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
private List<VendorsList> vendorsLists = null;
private ArrayList<VendorsList> arrayListVendorsList = null;
AppCompatActivity act;
public VendorsListAdapter(Context context,
List<VendorsList> vendorsLists) {
mContext = context;
this.vendorsLists = vendorsLists;
arrayListVendorsList = new ArrayList<>(vendorsLists);
inflater = LayoutInflater.from(mContext);
act = (AppCompatActivity) context;
}
public class ViewHolder {
TextView vendorNameTv;
}
#Override
public int getCount() {
return vendorsLists.size();
}
#Override
public VendorsList getItem(int position) {
return vendorsLists.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.lv_items_vendors_list, null);
holder.vendorNameTv = view.findViewById(R.id.lv_items_vendors_name_tv);
holder.vendorNameTv.setTypeface(StaticMethods.customFont(act, "Quicksand-Regular.otf"));
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.vendorNameTv.setText(vendorsLists.get(position).getVendorName());
return view;
}
/**
* Filter Class for item searching
*
* #param charText Text to be searched
*/
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendorsLists.clear();
if (charText.length() == 0) {
vendorsLists.addAll(arrayListVendorsList);
} else {
for (VendorsList vendorsList : arrayListVendorsList) {
if (vendorsList.getVendorName().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendorsLists.add(vendorsList);
}
}
}
notifyDataSetChanged();
}}
I have implement filter in android recyclerview adapter. But problem is that when I filtered item than position of item changed. I need the original position of the item after filter? How can i get it?
Here is my code:
public class SearchAdapter extends SelectableAdapter<SearchAdapter.ViewHolder> implements Filterable {
static ArrayList<SingleHadishDisplayModel> singleHadishDisplayModels;
ArrayList<SingleHadishDisplayModel> singleHadishDisplayModelsFilter;
public ViewHolder.ClickListener clickListener;
Context context;
public SearchAdapter(ArrayList<SingleHadishDisplayModel> singleHadishDisplayModels) {
this.singleHadishDisplayModelsFilter = singleHadishDisplayModels;
if (singleHadishDisplayModels != null) {
this.singleHadishDisplayModels = new ArrayList<>(singleHadishDisplayModels);
} else {
this.singleHadishDisplayModels = null;
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.search_adapter, parent, false);
ViewHolder vh = new ViewHolder(v, clickListener);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.topic.setText(singleHadishDisplayModelsFilter.get(position).topic);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Contants.clickPos=position;
/*long id = SearchAdapter.getItemId(position);
Toast.makeText(context,Long.toString(id), Toast.LENGTH_SHORT).show();*/
Intent intent = new Intent(context, HadishDetails.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return singleHadishDisplayModelsFilter.size();
}
public long getItemId(int position) {
int itemID;
// orig will be null only if we haven't filtered yet:
if (singleHadishDisplayModels == null) {
itemID = position;
} else {
itemID = singleHadishDisplayModels.indexOf(singleHadishDisplayModels.get(position));
}
return itemID;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint.length() == 0) {
filterResults.values = SearchAdapter.this.singleHadishDisplayModels;
return filterResults;
}
String searchString = constraint.toString().toLowerCase();
List<SingleHadishDisplayModel> filteredList = new ArrayList<>();
filterResults.values = filteredList;
for (SingleHadishDisplayModel tableSelectionDTO : SearchAdapter.this.singleHadishDisplayModels) {
if (tableSelectionDTO.topic.toLowerCase().contains(searchString)) {
filteredList.add(tableSelectionDTO);
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
SearchAdapter.this.singleHadishDisplayModelsFilter = (ArrayList<SingleHadishDisplayModel>) results.values;
SearchAdapter.this.notifyDataSetChanged();
}
};
return filter;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView topic;
private ClickListener listener;
public ViewHolder(View itemView, ClickListener clickListener) {
super(itemView);
this.listener = clickListener;
topic = (TextView) itemView.findViewById(R.id.topic_search);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View v) {
if (listener != null) {
listener.onItemClicked(getAdapterPosition());
}
}
#Override
public boolean onLongClick(View view) {
if (listener != null) {
return listener.onItemLongClicked(getAdapterPosition());
}
return false;
}
public interface ClickListener {
public void onItemClicked(int position);
public boolean onItemLongClicked(int position);
}
}
}
My activity:
public class SearchActivity extends AppCompatActivity implements SearchAdapter.ViewHolder.ClickListener {
private RecyclerView mRecyclerView;
public SearchAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<SingleHadishDisplayModel> singleHadishDisplayModels;
SingleHadishDisplayModel singleHadishDisplayModel;
int positionClick;
public static final String POST_ID = "postID";
FloatingSearchView floatingSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//floatingSearchView= (FloatingSearchView) findViewById(R.id.floating_search_view);
singleHadishDisplayModels = new ArrayList<SingleHadishDisplayModel>();
singleHadishDisplayModels = Contants.singleHadishDisplayModelsSaved;
mRecyclerView = (RecyclerView) findViewById(R.id.search_reycler);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new SearchAdapter(singleHadishDisplayModels);
mRecyclerView.setAdapter(mAdapter);
/* floatingSearchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
#Override
public void onSearchTextChanged(String oldQuery, final String newQuery) {
mAdapter.clearSelection();
mAdapter.getFilter().filter(newQuery);
}
});*/
EditText et = (EditText) findViewById(R.id.search_et);
et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
SearchActivity.this.mAdapter.getFilter().filter(cs);
Toast.makeText(SearchActivity.this, Integer.toString(arg1), Toast.LENGTH_SHORT).show();
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChange(Editable arg0) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onItemClicked(int position) {
positionClick = position;
// Intent intent =new Intent(SearchActivity.this,HadishDetails.class);
//startActivity(intent);
// Contants.clickPos=position;
}
#Override
public boolean onItemLongClicked(int position) {
return false;
}
}
Use This Codes :
int pos = list.indexOf(arraylist1.get(getAdapterPosition()));
Here list is the original list and arrayList is filtered items list.
Try this code..
make interface into adapter for handling click event like this way..
OnItemClick onItemClick;
public void setOnItemClick(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
public interface OnItemClick {
void getPosition(String data); //pass any data to shared it.
}
bindview method changes..
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.topic.setText(singleHadishDisplayModelsFilter.get(position).topic);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Contants.clickPos=position;
/*long id = SearchAdapter.getItemId(position);
Toast.makeText(context,Long.toString(id), Toast.LENGTH_SHORT).show();*/
onItemClick.getPosition("your data");
// Intent intent = new Intent(context, HadishDetails.class);
// context.startActivity(intent);
}
});
}
after adapter bind into recycler view call below code..
adpater.setOnItemClick(new RecyclerViewAdpater.OnItemClick() {
#Override
public void getPosition(String data) {
// hear update your value for check into if condition.
Intent intent = new Intent(context, HadishDetails.class);
context.startActivity(intent);
adpater.notifyDataSetChanged();
}
});
old position :
#Override
public long getItemId(int position) {
int itemID;
// mOriginalValues will be null only if we haven't filtered yet:
if (mOriginalValues == null)
{
itemID = position;
}
else
{
itemID = mOriginalValues.indexOf(mObjects.get(position));
}
return itemID;
}
Here, mOriginalValues is the list after filtering, mObjects is the old list which was passed to the adapter, so when click on the list in onItemClick(AdapterView<?> adapterView, View view, int position, long l) the old position is :
int oldPositionAfterFilter = (int) mainAdapter.getItemId(position);
so, always the real position even after filtering :
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position , long l) {
// always the real position even after filtering :
int oldPosition = (int) mainAdapter.getItemId(position);
String filePath = bs_filePathList.get(oldPosition);// always the original string;
bs_fileOptions(filePath);
}
});
I have search field,When i opened activity i am getting some data, i populated those data into list view Custom row. In custom row i have Text view,edit Text, textViewCancelImage. When i got response from server,parsing those response and fetch into custom rows.After that i enter some data in search field and i will get some suggestions.If i select any suggestion then i am populating same custom row to List View. When i clicked any suggestion i am getting selected value and populating same custom row. But all previous custom row Edit Text's values also changed to 0. And i am unable to delete row when i click cancel Image.
please check Activity
public class MaintainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pDialog;
private ResultVO resLogin;
private Button updateMRL,clearMRL;
#InjectView(R.id.listViewReorderLevel)
protected ListView reorderLevelListView;
private AutoCompleteTextView searchField;
OrderAdapter reorderAdapter;
ArrayList<OrderLevelsListBO> OrderLevelsListBOs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reorder_level);
new GetTradeNamesListAsyncTask().execute();
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(android.R.color.transparent);
updateMRL = (Button) findViewById(R.id.btnUpdateMRL);
clearMRL = (Button) findViewById(R.id.btnClearMRL);
searchField = (AutoCompleteTextView) findViewById(R.id.searchAutoCompleteTextViewMRL);
searchField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchField.getWindowToken(), 0);
SimpleDataBO simpleDataBO = (SimpleDataBO) adapterView.getAdapter().getItem(position);
String drugName = simpleDataBO.getData();
OrderLevelsListBO OrderLevelsListBO = new OrderLevelsListBO();
OrderLevelsListBO.setTradeCompositeId(drugName);
OrderLevelsListBO.setReorderLevelInBaseUnit("0");
OrderLevelsListBOs.add(OrderLevelsListBO);
reorderAdapter.notifyDataSetChanged();
searchField.setText("");
}
});
class GetTradeNamesListAsyncTask extends AsyncTask<String, String, String> {
private ResultVO resGetTCI;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... args) {
try {
HeaderParms HeaderParms = ICommonMethods.setHeaderParams(MaintainReorderLevelActivity.this);
APIServicesImpl services = new APIServicesImpl();
resGetTCI = services.get(SimpleDataArrayListBO.class, IUrlsUtil.URL_KYM_GET_TCI, HeaderParms);
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return null;
}
protected void onPostExecute(String file_url) {
if (resGetTCI != null) {
int appStatusCode = resGetTCI.getAppStatusCode();
if (appStatusCode == Constants.APP_STATUS_CODE_SUCCESS) {
SimpleDataArrayListBO simpleDataArrayListBO = (SimpleDataArrayListBO) resGetTCI.getPayload();
ArrayList<SimpleDataBO> simpleDataBOArrayList = simpleDataArrayListBO.getSimpleDataBOList();
if(simpleDataBOArrayList!=null) {
AutocomleteAdapter autocompleteAdapter = new AutocomleteAdapter(MaintainReorderLevelActivity.this, R.layout.drug_list_row_billing, simpleDataBOArrayList);
searchField.setAdapter(autocompleteAdapter);
searchField.setThreshold(1);
new OrderListAsy().execute();
}
} else {
String resMessage = resGetTCI.getMessages().get(0);
Toast.makeText(MaintainReorderLevelActivity.this, resMessage, Toast.LENGTH_SHORT).show();
}
} else {
ExceptionMessages.showAlertDialog(MaintainReorderLevelActivity.this, IExceptionUtil.NULL_RESPONSE_TITLE, IExceptionUtil.NULL_RESPONSE_MESSAGE, true);
}
}
}
class OrderListAsy extends AsyncTask<String, String, String> {
ResultVO resGetRL;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MaintainReorderLevelActivity.this);
pDialog.setMessage(Utility.USER_ID_EXISTS_MESSAGE);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
try {
HeaderParms HeaderParms = ICommonMethods.setHeaderParams(MaintainReorderLevelActivity.this);
APIServicesImpl services = new APIServicesImpl();
resGetRL = services.get(ReorderLevelsArrayListBO.class, IUrlsUtil.URL_RL_GET_STOCKS, HeaderParms);
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (resGetRL != null) {
int appStatusCode = resGetRL.getAppStatusCode();
if (appStatusCode == Constants.APP_STATUS_CODE_SUCCESS) {
ReorderLevelsArrayListBO reorderLevelsArrayListBO = (ReorderLevelsArrayListBO) resGetRL.getPayload();
OrderLevelsListBOs = reorderLevelsArrayListBO.getReorderLevelsList();
reorderAdapter = new OrderAdapter(MaintainReorderLevelActivity.this, OrderLevelsListBOs);
reorderLevelListView.setAdapter(reorderAdapter);
} else {
String resMessage = resGetRL.getMessages().get(0);
Toast.makeText(MaintainReorderLevelActivity.this, resMessage, Toast.LENGTH_SHORT).show();
}
} else {
ExceptionMessages.showAlertDialog(MaintainReorderLevelActivity.this, IExceptionUtil.NULL_RESPONSE_TITLE, IExceptionUtil.NULL_RESPONSE_MESSAGE, true);
}
}
}
}
MyAdapter class:
public class OrderAdapter extends BaseAdapter {
private Activity context;
ArrayList<OrderLevelsListBO> data;
OrderLevelsListBO OrderLevelsListBO;
public OrderAdapter(Activity context, ArrayList<OrderLevelsListBO> data) {
super();
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
EditText etReorderLevel;
TextView txtRLTradeName;
TextView txtDeleteMRL;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
OrderLevelsListBO = data.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.reorder_level_row, null);
holder = new ViewHolder();
holder.etReorderLevel = (EditText) convertView.findViewById(R.id.edtReorderLevel);
holder.txtRLTradeName = (TextView) convertView.findViewById(R.id.txtRLTradeName);
holder.txtDeleteMRL = (TextView) convertView.findViewById(R.id.txtDeleteMRL);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position % 2 == 1) {
convertView.setBackgroundColor(context.getResources().getColor(R.color.UPDATE_STOCK_LINE));
} else {
convertView.setBackgroundColor(context.getResources().getColor(R.color.WHITE));
}
if (OrderLevelsListBO.getTradeCompositeId() != null) {
holder.txtRLTradeName.setText(OrderLevelsListBO.getTradeCompositeId());
}
if (OrderLevelsListBO.getReorderLevelInBaseUnit() != null) {
holder.etReorderLevel.setText(OrderLevelsListBO.getReorderLevelInBaseUnit());
}
holder.etReorderLevel.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!holder.etReorderLevel.getText().toString().equals("")) {
String reorderQuantity = holder.etReorderLevel.getText().toString();
data.get(position).setReorderLevelInBaseUnit(reorderQuantity);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.txtDeleteMRL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.remove(position);
notifyDataSetChanged();
}
});
// OrderLevelsListBOs = data;
return convertView;
}
}
Why Don't you use recyclerview instead of a listview ?
Anyway if you go with the intention of using a listview, you've to do is create a method in your custom adapter.
Something like this:
public void addData(OrderLevelsListBO orderLevelsListBO) {
data.add(orderLevelsListBO);
}
And you call this method when you add a item.
reorderAdapter.addData(orderLevelsListBO);
In my application I have three fragment with ViewPager. one of this fragments i have simple Arraylist as ListView from phones contact list and i'm trying to filter that after typing into edittext.
but doesn't refresh until softkeyboard is visible and I must have to hide keyboard to refresh list view by filtered strings.
For example:
filter listview by "a":
adapter.getFilter().filter("a");
My adapter:
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.dir_image + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}
softkeyboard status status in Manifest for ActivityMain. this class have view pager with three fragment:
<activity android:name=".Activities.ActivityBootstrap" android:windowSoftInputMode="adjustPan" android:screenOrientation="portrait"/>
other way to do Filter in fragment without Adapter's ability
edt_sample.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 = edt_sample.getText().toString();
filter(text);
}
});
public void filter(String charText) {
drinks.clear();
if (charText.length() == 0) {
drinks.addAll(contact_list);
} else {
for (ContactLists wp : contact_list) {
if (wp.getContact_name().contains(charText)) {
drinks.add(wp);
}
}
}
contact_list.clear();
contact_list.addAll(drinks);
adapter.notifyDataSetChanged();
}
ListView succesful filtered by when i close or hide softkeyboard that refresh with nw items.
You're not making use of your adapter filter as I see from the code posted by you. I'll post here an example filter and how to call it (kept all your variable names to make it easier).
The 'NameFilter' class, inside your adapter class:
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
The 'TextWatcher' interface method implementation in your list fragment:
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
String text = searchView.getText().toString();
NameFilter itemFilter = (NameFilter) adapter.getFilter();
itemFilter.filter(text);
}
Also, some observations:
if 'ContactLists' is a contact, name it 'Contact', to avoid confusion
I would use a 'SearchView', instead of an 'EditText'
I don't know how you get the contact list, but there's a guide about it here (if you didn't look at it already)
It is very simple to implement. Please follow these below steps:
Step 1:
Initialize Edittext:
editTextVideoFolderSearch = (EditText) rootView.findViewById(R.id.editTextVideoFolderSearch);
Step 2:
Add TextChangedListener on this edittext. like:
editTextVideoFolderSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence t, int start, int before,
int count) {
videoDetailBeansSearch.clear();
for (int i = 0; i < videoDetailBeans_total.size(); i++) {
if (videoDetailBeans_total.get(i).getAlbum().toLowerCase()
.contains(t)) {
videoDetailBeansSearch.add(videoDetailBeans_total.get(i));
}
}
if (videoDetailBeansSearch.size() > 0) {
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeansSearch));
} else {
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeansSearch));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Step 3: you have to make different beans for populating the adapter in list view:
private ArrayList<MediaDetailBean> videoDetailBeansSearch = new ArrayList<MediaDetailBean>();
private ArrayList<MediaDetailBean> videoDetailBeans_total = new ArrayList<MediaDetailBean>();
private ArrayList<MediaDetailBean> videoDetailBeans_delete = new ArrayList<MediaDetailBean>();
Step 4: Polulate the list at the time of Activity or fragment loaded:
public class GetVideoAsynctask extends AsyncTask<String, String,Object[]> {
ProgressDialog progressDialog ;
String response = "";
int offset, limit;
public GetVideoAsynctask(int offset1, int limit1) {
offset = offset1;
limit = limit1;
}
#Override
public void onPreExecute() {
progressDialog = ProgressDialog.show(getActivity(),"Loading...", "Please Wait");
}
#Override
public Object[] doInBackground(String... params) {
return AppParsing.getMediaDetails(getActivity(), AppPreferenceUtils.getChildUploadDeviceId(getActivity()),
AppPreferenceUtils.getChildRaId(getActivity()),"2", offset, limit,"3");
//// type=1 for image,2 for video,3 for audio
}
#SuppressWarnings("unchecked")
#Override
public void onPostExecute(Object[] result) {
progressDialog.cancel();
try
{
boolean status = (Boolean) result[0];
response = (String) result[1];
if(status)
{
videoDetailBeans = (ArrayList<MediaDetailBean>) result[2] ;
for (int i = 0; i < videoDetailBeans.size(); i++) {
videoDetailBeans_total.add(videoDetailBeans.get(i));
}
isCheck_video = new boolean[videoDetailBeans_total.size()];
for(int i=0;i<videoDetailBeans_total.size();i++)
{
if(!GRID_DATA.contains(videoDetailBeans_total.get(i).getAlbum()))
{
GRID_DATA.add(videoDetailBeans_total.get(i).getAlbum());
}
}
video_folder_gridView.setAdapter(new AlbumGridAdapter(getActivity(), videoDetailBeans_total));
//Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();
}
else
{
response = (String) result[1];
AppUtils.showDialog(getActivity(), response);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Step 5: Set the listview adapter like:
new GetVideoAsynctask(offset1, limit1).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Step 6: Most important thinning is i am taking load more list view here:
com.costum.android.widget.LoadMoreListView) video_folder_gridView = (com.costum.android.widget.LoadMoreListView) rootView.findViewById(R.id.video_folder_gridView);
Step 7: In my xml i am declaring like this:
<com.costum.android.widget.LoadMoreListView
android:id="#+id/video_folder_gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
Feel free if you have any query regarding this concept.
This is my implementation of Filter which filters while you type a single letter.This is the Activity implementation...
public class MessagesActivity extends Activity{
private ListView msgListView;
private EditText mSearchContent;
private MessagesAdapter msgAdapter;
public static ArrayList<MessagesBean> allMsgsList = new ArrayList<MessagesBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
init();
msgAdapter = new MessagesAdapter(getApplicationContext(), allMsgsList, MessagesActivity.this);
msgListView.setAdapter(msgAdapter);
}
private void init() {
// TODO Auto-generated method stub
msgListView = (ListView) findViewById(R.id.messages_list);
msgListView.setOnScrollListener(this);
mSearchContent.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable s) {
msgAdapter.getFilter().filter(s.toString());
}
});
}
This is the Adapter implementation
public class MessagesAdapter extends BaseAdapter implements Filterable {
private Context mcontext;
private ArrayList<MessagesBean> all_details, dup_all_details;
private LayoutInflater inflater;
private DisplayImageOptions options;
private CustomClickLisntener clickLisntener;
private MessagesBean mMessagesBean;
private ViewHolder selectedHolder;
private ListViewFilter listviewFilter;
// int pos = 0;
public MessagesAdapter(Context context, ArrayList<MessagesBean> all_list, CustomClickLisntener lisntener) {
mcontext = context;
all_details = all_list;
clickLisntener = lisntener;
inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
dup_all_details = all_list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return all_details.size();
}
#Override
public MessagesBean getItem(int position) {
// TODO Auto-generated method stub
return all_details.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
static class ViewHolder {
TextView user_name, msg_sub, msg_content, msg_time;
ImageView user_image;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_item_inbox_msg, null);
viewholder.user_name = (TextView) convertView.findViewById(R.id.user_name);
viewholder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);
viewholder.msg_sub = (TextView) convertView.findViewById(R.id.msg_subject);
viewholder.user_image = (ImageView) convertView.findViewById(R.id.user_image);
viewholder.msg_content = (TextView) convertView.findViewById(R.id.msg_content);
// viewholder.down_arrow.setTag(position);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
mMessagesBean = all_details.get(position);
viewholder.user_name.setText(mMessagesBean.getFirstname().trim() + " " + mMessagesBean.getLastname());
viewholder.msg_time.setText(DateDifferent.getDateDifferance(mMessagesBean.getSentDate()));
viewholder.msg_sub.setText(mMessagesBean.getSubject());
viewholder.msg_content.setText(mMessagesBean.getMessage());
ImageLoader.getInstance().displayImage(mMessagesBean.getUserimage(), viewholder.user_image, options);
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
if (listviewFilter == null) {
listviewFilter = new ListViewFilter();
}
return listviewFilter;
}
public class ListViewFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
constraint = constraint.toString();
ArrayList<MessagesBean> allitems = new ArrayList<MessagesBean>();
FilterResults filterresults = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
for (int i = 0; i < dup_all_details.size(); i++) {
if (dup_all_details.get(i).getFirstname().contains(constraint)
|| dup_all_details.get(i).getLastname().contains(constraint)) {
allitems.add(dup_all_details.get(i));
}
}
filterresults.count = allitems.size();
filterresults.values = allitems;
} else {
System.out.println(" iam here..." + all_details.size());
synchronized (this) {
filterresults.count = allitems.size();
filterresults.values = allitems;
}
}
return filterresults;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// TODO Auto-generated method stub
all_details = (ArrayList<MessagesBean>) results.values;
MessagesActivity.allMsgsList = all_details;
MessagesAdapter.this.notifyDataSetChanged();
}
}
}
You can do it like:
public void filter(String charText) {
drinks.clear();
if (charText.length() == 0) {
drinks.addAll(contact_list);
} else {
for (ContactLists wp : contact_list) {
if (wp.getContact_name().contains(charText)) {
drinks.add(wp);
}
}
}
contact_list.clear();
contact_list.addAll(drinks);
adapter.notifyDataSetChanged(contact_list);
}
and in your adapter:
public void notifyDataSetChanged(List<ContactLists> items){
this.categoryArrayList = items;
super.notifyDataSetChanged();
}
I'm trying to create a filter search (using EditText) to search through my custom ListView items. I've tried to do it but it seems, that there is something wrong, because when i try to search (type in EditText) nothing happens.
Could you please help me?
Thanks in advance! :)
MainActivity.java
public class MainActivity extends ActionBarActivity{
private ListView mListView;
private AnimalAdapter mAdapter;
ProgressBar mProgressBar;
EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add your initialization code here
Parse.initialize(this, "code", "code");
ParseObject.registerSubclass(Animal.class);
ParseAnalytics.trackAppOpened(getIntent());
View header = getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView = (ListView) findViewById(R.id.animal_list);
mListView.setVisibility(View.INVISIBLE);
mListView.addHeaderView(header);
mProgressBar = (ProgressBar) findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
mEditText = (EditText) findViewById(R.id.search_animal);
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// 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 onTextChanged(CharSequence s, int start, int before,
int count) {
System.out.println("Text ["+s+"] - Start ["+start+"] - Before ["+before+"] - Count ["+count+"]");
if (count < before) {
// We're deleting char so we need to reset the adapter data
mAdapter.resetData();
}
mAdapter.getFilter().filter(s.toString());
}});
}
public void updateData(){
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
query.orderByAscending("animal");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar.setVisibility(View.INVISIBLE);
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Intent refreshIntent = new Intent(MainActivity.this, MainActivity.class);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
refreshIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(refreshIntent);
overridePendingTransition(0,0);
return true;
}
return super.onOptionsItemSelected(item);
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
updateData();
return null;
}
#Override
protected void onPostExecute(Void result) {
mListView = (ListView) findViewById(R.id.animal_list);
// Pass the results into ListViewAdapter.java
mAdapter = new AnimalAdapter(MainActivity.this, new ArrayList<Animal>());
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
}
}
}
AnimalAdapter.java
public class AnimalAdapter extends ArrayAdapter<Animal> implements Filterable{
private Context mContext;
private List<Animal> mAnimals;
ImageLoader imageLoader;
ArrayAdapter<Animal> array;
DisplayImageOptions options;
Activity activity;
private Filter animalFilter;
#SuppressWarnings("deprecation")
public AnimalAdapter(Context context, List<Animal> objects) {
super(context, R.layout.animal_row_item, objects);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
this.mContext = context;
this.mAnimals = objects;
}
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.animal_row_item, null);
}
final Animal animal = mAnimals.get(position);
TextView animalView = (TextView) convertView.findViewById(R.id.animal_text);
TextView areaView = (TextView) convertView.findViewById(R.id.area_text);
final ImageView animalPic = (ImageView)convertView.findViewById(R.id.animal_pic);
final ProgressBar indicator = (ProgressBar)convertView.findViewById(R.id.progress);
indicator.setVisibility(View.VISIBLE);
animalPic.setVisibility(View.INVISIBLE);
//Setup a listener we can use to switch from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
animalPic.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View view, FailReason arg2) {
}
};
imageLoader.displayImage(getItem(position).getImgUrl(), animalPic,options, listener);
animalView.setText(animal.getAnimal());
areaView.setText(animal.getArea());
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MoreActivity.class);
intent.putExtra("about", animal.getAbout());
intent.putExtra("animal", animal.getAnimal());
intent.putExtra("imgUrl", animal.getImgUrl());
getContext().startActivity(intent);
}
});
return convertView;
}
public void resetData() {
mAnimals = mAnimals;
}
#Override
public Filter getFilter() {
if (animalFilter == null)
animalFilter = new AnimalFilter();
return animalFilter;
}
private class AnimalFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mAnimals;
results.count = mAnimals.size();
}
else {
// We perform filtering operation
List<Animal> nPlanetList = new ArrayList<Animal>();
for (Animal a : mAnimals) {
if (a.getAnimal().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nPlanetList.add(a);
}
results.values = mAnimals;
results.count = mAnimals.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
mAnimals = (List<Animal>) results.values;
notifyDataSetChanged();
}
}
}
}
Animal.java
#ParseClassName("Animal")
public class Animal extends ParseObject{
public Animal(){
}
public String getAnimal(){
return getString("animal");
}
public void setAnimal(String animal){
put("animal", animal);
}
public String getArea(){
return getString("area");
}
public void setArea(String area){
put("area", area);
}
public String getImgUrl(){
return getString("imgUrl");
}
public void setImgUrl(String imgUrl){
put("imgUrl", imgUrl);
}
public String getAbout(){
return getString("about");
}
public void setAbout(String about){
put("about", about);
}
}
Solved it. Just add mListView.setTextFilterEnabled(true);