ListView search not working - android

I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.
I am getting my data from JSON.
Here's my code:
UserList.java
public class UserList extends AppCompatActivity {
private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
search = (EditText) findViewById(R.id.search);
//Array List for Binding Data from JSON to this List
list = new ArrayList<>();
//Binding that List to Adapter
adapter = new MyArrayAdapter(this, list);
//Getting List and Setting List Adapter
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
search.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) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//Checking Internet Connection
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
} else {
Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
}
}
//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
int jIndex;
int x;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Progress Dialog for User Interaction
x=list.size();
if(x==0)
jIndex=0;
else
jIndex=x;
dialog = new ProgressDialog(UserList.this);
dialog.setTitle("Please Wait..."+x);
dialog.setMessage("Retrieving Data");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
//Getting JSON Object from Web Using okHttp
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);
//Check Length of Array...
int lenArray = array.length();
if(lenArray > 0) {
for( ; jIndex < lenArray; jIndex++) {
//Creating Every time New Object and adding to List
MyDataModel model = new MyDataModel();
JSONObject innerObject = array.getJSONObject(jIndex);
String name = innerObject.getString(Keys.KEY_NAME);
model.setName(name);
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
//Checking if List size if more than zero then update ListView
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
}
}
}
}
I have implemented the filter method in my ArrayAdapter class.
Here's my ArrayAdapter class:
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
this.arrayList.addAll(modelList);
}
#Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
vh.textViewName.setText(item.getName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewName;
private ViewHolder(RelativeLayout rootView, TextView textViewName) {
this.rootView = rootView;
this.textViewName = textViewName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
return new ViewHolder(rootView, textViewName);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
for (MyDataModel wp : arrayList) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(wp);
}
}
}
notifyDataSetChanged();
}

Call search function from aftertTexChange
search.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) {
// i have updated this
String text = e.toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
});
now your search method should like this
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
// add this one here
notifyDataSetChanged();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
// change this for loop
for (int i = 0; i< arrayList.size(); i++) {
if (arrayList.get(i).getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(arrayList.get(i));
}
}
}
notifyDataSetChanged();
}

Related

Search in listview on android

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.

TextChangedListener not doing anything

I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.
I am getting my data from JSON.
Here's my code:
UserList.java
public class UserList extends AppCompatActivity {
private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
search = (EditText) findViewById(R.id.search);
//Array List for Binding Data from JSON to this List
list = new ArrayList<>();
//Binding that List to Adapter
adapter = new MyArrayAdapter(this, list);
//Getting List and Setting List Adapter
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
search.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) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
//Checking Internet Connection
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
} else {
Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
}
}
//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
int jIndex;
int x;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Progress Dialog for User Interaction
x=list.size();
if(x==0)
jIndex=0;
else
jIndex=x;
dialog = new ProgressDialog(UserList.this);
dialog.setTitle("Please Wait..."+x);
dialog.setMessage("Retrieving Data");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
//Getting JSON Object from Web Using okHttp
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);
//Check Length of Array...
int lenArray = array.length();
if(lenArray > 0) {
for( ; jIndex < lenArray; jIndex++) {
//Creating Every time New Object and adding to List
MyDataModel model = new MyDataModel();
JSONObject innerObject = array.getJSONObject(jIndex);
String name = innerObject.getString(Keys.KEY_NAME);
model.setName(name);
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
//Checking if List size if more than zero then update ListView
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
}
}
}
}
I have implemented the filter method in my ArrayAdapter class.
Here's my ArrayAdapter class:
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
this.arrayList.addAll(modelList);
}
#Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
vh.textViewName.setText(item.getName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewName;
private ViewHolder(RelativeLayout rootView, TextView textViewName) {
this.rootView = rootView;
this.textViewName = textViewName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
return new ViewHolder(rootView, textViewName);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
for (MyDataModel wp : arrayList) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(wp);
}
}
}
notifyDataSetChanged();
}
You need to create one more arryList to filter data.
public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;
public MyArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
this.arrayList = new ArrayList<MyDataModel>();
this.arraylist.addAll(modelList);
}
Now in Filter method you have to compare on the basis of arrayList
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
modelList.clear();
if (charText.length() == 0) {
modelList.addAll(arrayList);
} else {
for (MyDataModel wp : arrayList) {
if
(wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
modelList.add(wp);
}
}
}
notifyDataSetChanged();
}

Problems with notifyDataSetChanged(). All edittext's value is changing

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

Android ListView does not refresh by Filter

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

Android filter listview custom adapter

Hello everybody I'm doing an app which has an edittext to search for items on the listview. If the user types a letter. The data come from my json string (database) and then display on my listview. So far this is what I've tried:
ListViewAdapter adapter2;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> list = new ArrayList<String>();
wsSearch.addTextChangedListener(new TextWatcher (){
public void afterTextChanged(Editable cs) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
//BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs);
String searchString = cs.toString();
if(searchString.length() != 2) {
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arraylist);
listview.setAdapter(adapter2);
return;
}
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < arraylist.size(); i++)
{
String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE);
if (searchString.equalsIgnoreCase(currentString))
{
arrayTemplist.add(arraylist.get(i));
}
}
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
listview.setAdapter(adapter2);
}
});
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter2 = new ListViewAdapter(Activity2.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter2);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
What I want to achieve, if the user types a letter like B, all the items that start with the said letter should be filtered. But using the code I posted above, it does not do exactly what I want. It just filters whenever I typed the whole item name. Any ideas? Your help will be greatly appreciated. Thanks.
As far as I can see you are only checking if the two Strings match exactly.
You might want to use boolean startsWith(String prefix)
Which would make something like
if (currentString.trim().toLowerCase().startsWith(searchString.trim().toLowerCase()))
{
arrayTemplist.add(arraylist.get(i));
}
I got complete solution, i put filter method in custom adapter for multiple fields search functionality.
Note: for image loading i took lazy loading so you need ImageLoader.java, FileCache.java, Utils.java and MemoryCache.java.
Check bellow code.....
list_layout.xml ( layout folder )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#ffffff" >
<EditText
android:id="#+id/et_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="search...."
android:paddingLeft="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_height="match_parent"
android:layout_below="#+id/et_search">
</ListView>
</RelativeLayout>
custom_row.xml ( layout folder )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#33B5E5" >
<ImageView
android:id="#+id/image_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="23dp"
android:layout_marginLeft="23dp"
android:layout_marginTop="23dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/txt_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/image_view"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/image_view"
android:text="id"
android:textColor="#ffffff" />
<TextView
android:id="#+id/txt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txt_id"
android:layout_below="#+id/txt_id"
android:text="name"
android:textColor="#ffffff" />
</RelativeLayout>
put sample.json file in assets folder
sample.json
{
"sample":[
{
"id":"1",
"name":"nirav kalola",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"def"
},
{
"id":"2",
"name":"abc",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"abc"
},
{
"id":"3",
"name":"def",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"ghi"
},
{
"id":"55",
"name":"ghi",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"jkl"
},
{
"id":"5",
"name":"jkl",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"mno"
},
{
"id":"11",
"name":"mno",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"pqr"
},
{
"id":"10",
"name":"nirav007",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"stu"
}
]
}
ListActivity.java ( src folder )
public class ListActivity extends Activity {
private ListView listView;
private ProgressDialog progressDialog;
private List<SampleData> sampleData;
private ArrayList<SampleData> sampleList;
private SampleAdapter sampleAdapter;
private EditText etSearch;
ArrayList<SampleData> arraylist = new ArrayList<SampleData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
listView=(ListView) findViewById(R.id.list_view);
BackGroundTask bt = new BackGroundTask();
bt.execute();
etSearch=(EditText) findViewById(R.id.et_search);
etSearch.setSingleLine(true);
etSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
sampleAdapter.filter(text);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
private class BackGroundTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog = new ProgressDialog(ListActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... arg0) {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray jsonArray = jsonObject.getJSONArray("sample");
sampleData=new ArrayList<SampleData>();
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObjectInside = jsonArray.getJSONObject(i);
String id = jsonObjectInside.getString("id");
String name = jsonObjectInside.getString("name");
String imagePath = jsonObjectInside.getString("image");
String description = jsonObjectInside.getString("description");
sampleData.add(new SampleData(id, name, imagePath, description));
Log.e("id",id+"");
Log.e("name",name+"");
Log.e("imagPath",imagePath+"");
Log.e("description",description+"");
}
handlePostsList(sampleData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
progressDialog.dismiss();
}
}// End of Background AsyncTask
private void handlePostsList(final List<SampleData> sampleData) {
this.sampleData = sampleData;
runOnUiThread(new Runnable() {
public void run() {
try {
// logic for retrieve data first time in list view.
sampleList = new ArrayList<SampleData>();
for (int i = 0; i < sampleData.size(); i++) {
sampleList.add(new SampleData(sampleData.get(i).getId().toString(),sampleData.get(i).getName().toString(),sampleData.get(i).getImage().toString(),sampleData.get(i).getDescription().toString()));
}
sampleAdapter= new SampleAdapter(ListActivity.this, sampleList);
listView.setAdapter(sampleAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class SampleAdapter extends BaseAdapter
{
Context context;
List<SampleData> sampleData=null;
ArrayList<SampleData> arraylist;
LayoutInflater inflater;
ImageLoader imageLoader;
public SampleAdapter(Context context, List<SampleData> sampleData) {
this.context = context;
this.sampleData = sampleData;
this.arraylist = new ArrayList<SampleData>();
this.arraylist.addAll(sampleData);
imageLoader=new ImageLoader(ListActivity.this);
}
public class ViewHolder {
TextView txtID,txtName,txtDescription;
ImageView image;
}
public int getCount() {
return sampleData.size();
}
public Object getItem(int position) {
return sampleData.get(position);
}
public long getItemId(int position) {
return sampleData.indexOf(getItem(position));
}
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.txtID = (TextView) convertView.findViewById(R.id.txt_id);
holder.txtName = (TextView) convertView.findViewById(R.id.txt_name);
holder.image = (ImageView) convertView.findViewById(R.id.image_view);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtID.setText(sampleData.get(position).getId());
holder.txtName.setText(sampleData.get(position).getName());
imageLoader.DisplayImage(sampleData.get(position).getImage(), holder.image);
// convertView.setOnClickListener(new OnClickListener() {
// Intent intent=null;
// #Override
// public void onClick(View v) {
// Log.e("description....",sampleData.get(position).getDescription()+"");
// intent=new Intent(ListActivity.this, DetailActivity.class);
// intent.putExtra("description", sampleData.get(position).getDescription());
// startActivity(intent);
// finish();
// }
// });
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
sampleData.clear();
if (charText.length() == 0) {
sampleData.addAll(arraylist);
} else {
for (SampleData st : arraylist) {
if (st.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}else if (st.getId().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}
else if (st.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}
}
}
notifyDataSetChanged();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("sample.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
SampleData.java ( src folder )
public class SampleData
{
private String id;
private String name;
private String image;
private String description;
public SampleData(String id, String name, String image, String description) {
super();
this.id = id;
this.name = name;
this.image = image;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
add following permissions in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
thats it..
enjoy coding
//Main Activity
Intent intent = new Intent(getApplicationContext(),
ListActivity.class);
intent.putExtra("name", name);
intent.putExtra("number", number);
startActivity(intent);
Then
ListActivity.class
EditText search;
ListView lvDetail;
Contact data;
MyBaseAdapter adapter;
ArrayList<Contact> myList = new ArrayList<Contact>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
lvDetail = (ListView) findViewById(R.id.lvCustomList);
search = (EditText) findViewById(R.id.inputSearch);
String[] name = getIntent().getStringArrayExtra("name");
String[] number = getIntent().getStringArrayExtra("number");
// System.out.println((1>2?1:(1==2?1:(2>3?2:3))));
for (int i = 0; i < name.length; i++) {
data = new Contact();
data.setName(name[i]);
data.setPhonenum(number[i]);
data.setImgResId(img[i]);
myList.add(data);
}
adapter = new MyBaseAdapter(getApplicationContext(), myList);
lvDetail.setAdapter(adapter);
lvDetail.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#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
}
});
}
//Custom Adapter
public class MyBaseAdapter extends BaseAdapter {
ArrayList<Contact> myList = new ArrayList<Contact>();
LayoutInflater inflater;
Context context;
private ArrayList<Contact> privatearray;
public MyBaseAdapter(Context context,ArrayList<Contact> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
privatearray=new ArrayList<Contact>();
privatearray.addAll(myList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
//LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.layout_list_item, arg2, false);
TextView title, detail;
ImageView i1;
i1=(ImageView)row.findViewById(R.id.ivIcon);
title = (TextView) row.findViewById(R.id.name);
detail = (TextView) row.findViewById(R.id.phonenumber);
i1=(ImageView)row.findViewById(R.id.ivIcon);
//ListActivity activity=(ListActivity)Arrays.asList(myList)[0];
//ListData data=myList.get(0);
// Log.d("list", String.valueOf(myList.size())+" "+String.valueOf(data.getDescription()));
i1.setImageResource(myList.get(position).getImgResId());
title.setText(myList.get(position).getName());
detail.setText(myList.get(position).getPhonenum());
return (row);
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
myList.clear();
if(charText.length()==0){
myList.addAll(privatearray);
}
else{
for (Contact c : privatearray) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
myList.add(c);
}
}
}
notifyDataSetChanged();
}
}
//and Model
public class Contact {
String phonenum;
String name;
int imgResId;
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
You could give this a try:
public class MyAdapter extends ArrayAdapter<Model> {
public MyAdapter(Context context, int textViewResourceId,
List<model> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tx = (TextView)convertView;
SpannableString text = getItem(position);
for(char:typedChar)
if(tx.getText().contains(char)){
// make "text" (characters pos-1 to pos) red
text.setSpan(new ForegroundColorSpan(Color.RED),
tx.getText().indexOf(char) - 1, tx.getText().indexOf(char), 0);
textView.setText(text, BufferType.SPANNABLE);
}
}
}
Then Finally Register Editext here:
edit.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
//Modify letter here by simple parsing
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
Hope this could help you ...
Update your own code only:
searchString = searchString.trim().toLowerCase();
for (int i = 0; i < arraylist.size(); i++)
{
String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE).trim().toLowerCase();
if (currentString.startsWith(searchString))
{
arrayTemplist.add(arraylist.get(i));
}
}
The code below maybe help you.
private ArrayList<HashMap<String, String>> arrayDatalist = new ArrayList<HashMap<String,String>>();
...
#Override
protected void onCreate(Bundle savedInstanceState) {
....
arrayDatalist.addAll(arraylist);
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayDatalist);
listview.setAdapter(adapter2);
searchInput.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){
if (searchInput.isEnabled()){
searchString = searchInput.getText().toString().trim().toLowerCase();
if (searchLocationOperation!=null && searchLocationOperation.getStatus().equals(Status.RUNNING)){
searchLocationOperation.cancel(true);
}
searchLocationOperation = new SearchLocationOperation(searchString);
searchLocationOperation.execute();
}
}
});
}
private class SearchLocationOperation extends AsyncTask<Void, Void, String> {
private ArrayList<HashMap<String, String>> searchResult = new ArrayList<HashMap<String,String>>();
private String searchString;
public SearchLocationOperation(String str){
searchString = str;
}
#Override
protected String doInBackground(Void... params) {
if (searchString.length() <= 2) {
searchResult.addAll(arraylist);
}else{
for (HashMap<String, String> rowItem: arraylist)
{
//if (rowItem.get(BAPTISMAL_SONG.TAG_TITLE).toLowerCase().contains(searchString)) //If get filter with any part of the name
if (rowItem.get(BAPTISMAL_SONG.TAG_TITLE).toLowerCase().startWiths(searchString))
{
searchResult.add(rowItem);
}
if (isCancelled()) return null;
}
}
return null;
}
#Override
protected void onPreExecute() {
//Show progress if needed
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
//Hide progress if showed
if (!isCancelled() && arrayDatalist!=null && adapter2!=null){
arrayDatalist.clear();
arrayDatalist.addAll(searchResult);
adapter2.notifyDataSetChanged();
}
super.onPostExecute(result);
}
}
arrayTemplist.clear();
for (int i = 0; i < mainArray.size(); i++) {
if (searchString.length()<= mainArray.get(i).length()) {
if (editText
.getText()
.toString()
.equalsIgnoreCase(
(String) mainArray.get(i).subSequence(0,
searchString.length()))) {
arrayTemplist.add(mainArray.get(i));
}
}
}
adapter = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
use this `onTextChanged() method, might be it will help you.

Categories

Resources