Search clears all object in ListView - android

I've got a problem with my search filter. When i start typing, all objects are gone and no search is performed. Only after refresh are they back. When I try to proof via Toast, that if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) in adapter is called, no toast views.
Do you have any idea, where the problem could be? Thanks in advance!
My MainActivity class with EditText listener
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();
}
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);
mListView.setTextFilterEnabled(true);
mEditText = (EditText) findViewById(R.id.search_animal);
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
mListView.setVisibility(View.VISIBLE);
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
mListView.setVisibility(View.VISIBLE);
String text = mEditText.getText().toString()
.toLowerCase(Locale.getDefault());
mAdapter.filter(text);
}
});
}
}
}
My Adapter class with filter method
public class AnimalAdapter extends ArrayAdapter<Animal> implements Filterable{
private Context mContext;
private List<Animal> mAnimals;
ImageLoader imageLoader;
ArrayList<Animal> array;
DisplayImageOptions options;
Activity activity;
private Filter animalFilter;
private List<Animal> animaly;
#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;
this.animaly = 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 int getCount() {}
return mAnimals.size();
public void filter(String text) {
if (text.length() == 0) {
mAnimals.addAll(animaly);
Toast.makeText(getContext(), "text 0", Toast.LENGTH_SHORT).show();
} else {
mAnimals.clear();
for (Animal wp : animaly) {
if (wp.getAnimal().toLowerCase(Locale.getDefault())
.contains(text)) {
Toast.makeText(getContext(), "contains", Toast.LENGTH_SHORT).show();
mAnimals.add(wp);
}
}}
notifyDataSetChanged();
}
}

I just solved this with doing it a little bit different way. For great tutorial check/codes:
For tutorial check this.
For the whole codes check this.
Good luck and have a great day!

Related

Error in list search

I'm having difficulty updating the data of a listview, I've developed the search function in the listview and I can search the data, but I need to access the details in detail, passing to an activity, when I do that the data that is passed is those of the id 0 of the first list ... that is, only the view is being updated and not the data. Does anyone know how to fix it?
Search Activity
public class PesquisaTesteActivity extends AppCompatActivity {
public static TextView txt;
public static List<PesquisaBD> lista_produtos;
public static ListView lv;
AdapterBDLocal adapter;
private Button btn;
public static ArrayList list = new ArrayList();
private EditText searchView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pesquisa_teste);
lv = (ListView)findViewById(R.id.lv2);
searchView = (EditText) findViewById(R.id.search);
lista_produtos = DataBaseClass.getInstance(getApplicationContext()).getAllProdutos();
txt = findViewById(R.id.textView);
adapter = new AdapterBDLocal(PesquisaTesteActivity.this, lista_produtos);
searchView.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) {
final List<PesquisaBD> filtro = filter(lista_produtos,s.toString());
adapter.setFilter(filtro);
lv.setAdapter(adapter);
}
});
btn = (Button) findViewById(R.id.btn_te);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(PesquisaTesteActivity.this, Scan3Activity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent inte = new Intent(PesquisaTesteActivity.this, DetalhesPesquisaActivity.class);
inte.putExtra("nome", lista_produtos.get(i).getNome_completo());
inte.putExtra("codigo", lista_produtos.get(i).getCodigo_barras());
inte.putExtra("imagem", lista_produtos.get(i).getImagem());
inte.putExtra("unidade", lista_produtos.get(i).getUnidade());
inte.putExtra("preco", lista_produtos.get(i).getPreco());
startActivity(inte);
}
});
lv.setAdapter(adapter);
}
private List<PesquisaBD> filter(List<PesquisaBD> lista, String query){
query = query.toLowerCase();
final List<PesquisaBD> filtro = new ArrayList<>();
for(PesquisaBD p : lista){
final String texte = p.getNome_completo().toLowerCase();
if(texte.startsWith(query)){
filtro.add(p);
}
}
return filtro;
}
}
Adapter
public class AdapterBDLocal extends BaseAdapter{
private Context mContext;
private List<PesquisaBD> produtosList = new ArrayList<>();
private Filter filter;
public AdapterBDLocal(Context mContext, List<PesquisaBD> 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 PesquisaBD p = produtosList.get(i);
ImageView img_produto_pesquisa = listItem.findViewById(R.id.img_produto_pesquisa);
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.getPreco());
TextView unidade = (TextView) listItem.findViewById(R.id.txt_unidade2);
unidade.setText(p.getUnidade());
ImageView btn_add = (ImageView)listItem.findViewById(R.id.btn_add);
ImageView btn_rem = (ImageView)listItem.findViewById(R.id.btn_rem);
if(p.getImagem() == null){
Picasso.with(mContext).load(R.drawable.ic_logo).fit().into(img_produto_pesquisa);
} else {
//Picasso.with(mContext).load(p.getImagem()).networkPolicy(NetworkPolicy.OFFLINE).fit().into(img_produto_pesquisa);
Glide.with(mContext).load(p.getImagem()).into(img_produto_pesquisa);
}
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;
}
public void setFilter(List<PesquisaBD> l) {
produtosList = new ArrayList<PesquisaBD>();
produtosList.addAll(l);
notifyDataSetChanged();
}
}
In your adapter use this :- produtosList.clear(); instead of
produtosList = new ArrayList<PesquisaBD>(); that is
public void setFilter(List<PesquisaBD> l) {
produtosList.clear();
produtosList.addAll(l);
notifyDataSetChanged(); }

Android searchView not searching the list until fully scrolled

I have a listview with a custom adapter, and Im trying to use SearchView with a CustomFilter. But the search is not "fully" working.
When I search for something that is on the viewable area of the listview, it is able to search, and all nonviewable area is not being included in the search.
Here is a video on whats going on:
https://youtu.be/2Z9FZMlNmGw
main
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_board_game_list, container, false);
this.listView = (ListView) view.findViewById(R.id.listView);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this.getContext());
databaseAccess.open();
List<String> boardgamesNames = databaseAccess.getNames();
List<String> urls = databaseAccess.getUrls();
adapter = new bgAdapter(getContext(), R.layout.row_layout);
adapterOriginal = new bgAdapter(getContext(), R.layout.row_layout);
databaseAccess.close();
listView.setAdapter(adapter);
int i = 0;
for(String name: boardgamesNames) {
boardgameListRow data = new boardgameListRow(urls.get(i), boardgamesNames.get(i));
i++;
adapter.add(data);
adapterOriginal.add(data);
}
listView.setDivider(null);
listView.setDividerHeight(0);
searchView = (SearchView)view.findViewById(R.id.searchId);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
adapter.getFilter().filter(newText);
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
BoardGameListFragment fragment= new BoardGameListFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
//adapter = adapterOriginal;
return true;
}
});
// Inflate the layout for this fragment
return view;
}
}
Here is the Adapter:
https://github.com/Shank09/AndroidTemp/blob/master/bgAdapter.java
I think you need to call notifyDataSetChanged() in onQueryTextChange
I fixed it, I was using the wrong variable in bgAdapter. Please remove this question if possible.
public class Listbyoperator extends Activity {
ListView lstdetail;
Activity act;
EditText search;
ArrayList<DetailModel> detail=new ArrayList<DetailModel>();
DetailaAdapter dadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listbyoperator);
act=this;
lstdetail=(ListView) findViewById(R.id.Listbyoperator_detaillist);
search=(EditText) findViewById(R.id.editsearch);
search.setPadding(10, 0, 0, 0);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
DetailModel d=new DetailModel("1","HARDIP","saahi");
detail.add(d);
DetailModel d1=new DetailModel("2","jalpa","sadfsadf");
detail.add(d1);
dadapter=new DetailaAdapter(act, detail);
lstdetail.setAdapter(dadapter);
dadapter.notifyDataSetChanged();
lstdetail.setEnabled(true);
}
}
/*Detail Model*/
public class DetailModel
{
public String d_id,d_name,d_decription;
public String getD_id() {
return d_id;
}
public void setD_id(String d_id) {
this.d_id = d_id;
}
public String getD_name() {
return d_name;
}
public void setD_name(String d_name) {
this.d_name = d_name;
}
public String getD_decription() {
return d_decription;
}
public void setD_decription(String d_decription) {
this.d_decription = d_decription;
}
public DetailModel(String s1,String s2,String s3)
{
this.d_id=s1;
this.d_name=s2;
this.d_decription=s3;
}
}
/*detail adapter */
public class DetailaAdapter extends BaseAdapter{
Context mContext;
private List<DetailModel> data=null;
private ArrayList<DetailModel> arraylist;
private static LayoutInflater inflater=null;
private static String String=null,valid;
public boolean flag=true;
public DetailaAdapter(Context context,List<DetailModel> data)
{
mContext = context;
this.data = data;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<DetailModel>();
this.arraylist.addAll(data);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_detail, null);
final TextView t1,t2,t3,t4,t5;
t1=(TextView)vi.findViewById(R.id.list_detail_text1);
t2=(TextView)vi.findViewById(R.id.list_detail_textview2);
t3=(TextView)vi.findViewById(R.id.list_detail_text2);
DetailModel da =new DetailModel(String, String,String);
da=data.get(position);
final String a1,a2,a3;
a1=da.d_id;
a2=da.d_name;
a3=da.d_decription;
t2.setText(a3);//description
t3.setText(a2);//name
return vi;
}
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll(arraylist);
}
else
{
for (DetailModel wp : arraylist)
{
if (wp.getD_decription().toLowerCase(Locale.getDefault()).contains(charText) || wp.getD_name().toLowerCase(Locale.getDefault()).contains(charText))
{
data.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);

Automatically load more items in ListView (XML parsing)

I've done XML parsing to ListView and right now do i need to implement load-more feature. I know how to indicat, when the user scrolled to the bottom and how to limit the number of items in a ListView. But is there any way how to show more items when the user scrolls to the end of the list?
Here is my adapter class:
public class ClubsAdapter extends ArrayAdapter<LeagueClub> {
ImageLoader imageLoader;
DisplayImageOptions options;
Context mContext;
public static List<LeagueClub> mClubs;
#SuppressWarnings("deprecation")
public ClubsAdapter(Context mContext, int textViewResourceId, List<LeagueClub> clubs) {
super(mContext, textViewResourceId, clubs);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
mClubs=clubs;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("PremierLeague", "getView pos = " + pos);
if(null == row){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
final ImageView clubLogo = (ImageView)row.findViewById(R.id.clubLogo);
TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView aboutTxt = (TextView)row.findViewById(R.id.aboutTxt);
TextView stadiumTxt = (TextView)row.findViewById(R.id.stadiumTxt);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
indicator.setVisibility(View.VISIBLE);
clubLogo.setVisibility(View.INVISIBLE);
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);
clubLogo.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View view, FailReason arg2) {
indicator.setVisibility(View.INVISIBLE);
ImageView imageView = (ImageView) view.findViewById(R.id.clubLogo);
imageView.setVisibility(View.VISIBLE);
}
};
imageLoader.displayImage(getItem(pos).getLogo(), clubLogo,options, listener);
nameTxt.setText(getItem(pos).getName());
aboutTxt.setText(getItem(pos).getAbout());
stadiumTxt.setText(getItem(pos).getStadium());
return row;
}
public int getCount() {
return mClubs.size(); //If i set return 10; it limits items to max 10
}
}
And here is my Fragment:
public class Fragment2 extends Fragment {
static PullToRefreshListView mListView;
static ClubsAdapter mAdapter;
Context mContext;
ProgressBar mProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_2, container, false);
mListView = (PullToRefreshListView) rootView.findViewById(R.id.pull_to_refresh_listview1);
mProgress = (ProgressBar) rootView.findViewById(R.id.loading_clubs);
mProgress.setVisibility(View.VISIBLE);
ClubsDownloadTask task = new ClubsDownloadTask();
task.execute();
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
mProgress.setVisibility(View.INVISIBLE);
ClubsDownloadTask task = new ClubsDownloadTask();
task.execute();
}
});
return rootView;
}
private class ClubsDownloadTask extends AsyncTask<Void, Void, Void>{
private ClubsAdapter mAdapter;
#Override
protected Void doInBackground(Void... arg0) {
try {
Downloader.DownloadFromUrl("http://dl.dropboxusercontent.com/s/h2qc41k2yy3c1ir/clubs.xml", getActivity().openFileOutput("clubs.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
}
protected void onPostExecute(Void result){
mListView.onRefreshComplete();
mProgress.setVisibility(View.INVISIBLE);
mAdapter = new ClubsAdapter(getActivity(), -1 , ClubsXmlPullParser.getItemsFromFile(getActivity()));
mListView.setAdapter(mAdapter);
if(ClubsAdapter.mClubs != null){
mAdapter.clear();
for (int i = 0; i < ClubsAdapter.mClubs.size(); i++) {
mAdapter.add(ClubsAdapter.mClubs.get(i));
}
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if(mListView.getRefreshableView().getCount()!=0&&mListView.getRefreshableView().getCount()>0&&mAdapter.getCount()!=0){
if (mListView.getRefreshableView().getLastVisiblePosition() == mListView.getRefreshableView().getAdapter().getCount() - 1
&& mListView.getRefreshableView()
.getChildAt(mListView.getRefreshableView().getChildCount() - 1)
.getBottom() <= mListView.getRefreshableView().getHeight()) {
//Here do I need to load more items
}
}
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getActivity().getCurrentFocus();
if(currentFocus != null) {
currentFocus.clearFocus();
}
}
}
});
}
}
}
}
Thanks for any suggestion!
You can use this adapter https://github.com/commonsguy/cwac-endless
With this adapter, when user scroll to end of list, it will call a function which you can implement to load more items.

Search filter in custom ListView

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

Categories

Resources