I am have a small problem in my custom dialog.
When the user search for an item in the listview, the list shows the right items, but if the user for example wants to search again, the listview shows the results from the previous search.
The problem:
How do I restore the listview after the first search?
My activity with the custom dialog
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
private void showDialog() {
dialog = new Dialog(this);
View view = getLayoutInflater().inflate(R.layout.material_list, null);
searchList = (ListView) view.findViewById(R.id.searchList);
dialog.setTitle("Välj ny artikel");
final MaterialAdapter adapter = new MaterialAdapter(
InformationActivity.this, materialList);
dialog.setContentView(view);
searchList.setAdapter(adapter);
searchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Materials itemMat = materialList.get(position);
resultProduct = itemMat.materialName;
resultProductNo = itemMat.materialNo;
result = resultProduct + " " + resultProductNo;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
search = (EditText) dialog.findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
cancel = (Button) dialog.findViewById(R.id.btnCancel);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
ok = (Button) dialog.findViewById(R.id.btnOK);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
product.setText(resultProduct);
productNo.setText(resultProductNo);
dialog.dismiss();
}
});
dialog.show();
}
}
My adapter
public class MaterialAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Materials> searchItemList = null;
ArrayList<Materials> materialList = new ArrayList<Materials>();
public MaterialAdapter(Context context, List<Materials> searchItemList) {
this.context = context;
inflater = LayoutInflater.from(context);
this.searchItemList = searchItemList;
this.materialList = new ArrayList<Materials>();
this.materialList.addAll(searchItemList);
}
#Override
public int getCount() {
return searchItemList.size();
}
#Override
public Object getItem(int position) {
return searchItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.d, null);
viewHolder = new ViewHolder();
viewHolder.tvMaterialName = (TextView) convertView
.findViewById(R.id.tvMaterialName);
viewHolder.tvMaterialNo = (TextView) convertView
.findViewById(R.id.tvMaterialNo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvMaterialName.setText((searchItemList.get(position))
.getMaterialName());
viewHolder.tvMaterialNo.setText((searchItemList.get(position))
.getMaterialNo());
return convertView;
}
public class ViewHolder {
TextView tvMaterialName;
TextView tvMaterialNo;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
searchItemList.clear();
if (charText.length() == 0) {
searchItemList.addAll(materialList);
} else {
for (Materials wp : materialList) {
if (wp.getMaterialName().toLowerCase(Locale.getDefault())
.startsWith(charText)) {
searchItemList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Thanks for the help :)
Try to change search.getText() to s.toString()
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
to
public void onTextChanged(CharSequence s, int start, int before, int count) {
resultText = s.toString().toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
A secondary thing, make materialList = searchItemList; And searchItemList empty which will be filled with search items (first run will be same elements of materialList.)
P.S Your adapter should implement Filterable in this case (implements Filterable)
#Override
public void afterTextChanged(Editable s) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
Try this and check whether it helps
Related
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(); }
I am using ArrayAdapter When I delete the first item from Listview.Its delete perfectly.But When I do delete the second item from the listview. Its not perfectly delete.
how can i do it?
Adapter coding
import android.widget.ArrayAdapter;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// final CartBean beans = getItem(position);
View view = convertView;
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_cart_row, parent, false);
viewHolder = new ViewHolder();
viewHolder.row_price = (TextView) view.findViewById(R.id.row_price);
viewHolder.et_quantity = (EditText) view.findViewById(R.id.cart_quantity);
viewHolder.row_item_name = (TextView) view.findViewById(R.id.row_item_name);
viewHolder.deleteButton = (ImageView) view.findViewById(R.id.iv_delete);
// viewHolder.rastaurantoffer = (ImageView) view.findViewById(R.id.rastaurantname2);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (viewHolder.textWatcher != null)
viewHolder.et_quantity.removeTextChangedListener(viewHolder.textWatcher);
final CartBean bean = getItem(position);
viewHolder.textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length()>0) {
viewHolder.row_price.setText(String.valueOf(df.format(Double.parseDouble(bean.getTotal_price()) * Integer.parseInt(charSequence.toString()))));
AppConstants.cartBeanArrayList.get(position).setQuantity(Integer.parseInt(charSequence.toString()));
}
}
#Override
public void afterTextChanged(Editable editable) {
Double totalPrice=0.0;
for (int i=0;i<AppConstants.cartBeanArrayList.size();i++)
{
totalPrice=totalPrice+(Double.parseDouble(AppConstants.cartBeanArrayList.get(i).getTotal_price()) * AppConstants.cartBeanArrayList.get(i).getQuantity());
Log.i("total_price12356",""+total_price);
}
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(df.format(totalPrice)));
}
};
viewHolder.row_price.setText("£."+String.valueOf(df.format(Double.parseDouble(cartBeans.get(position).getTotal_price()) * cartBeans.get(position).getQuantity())));
viewHolder.et_quantity.setText(String.valueOf(cartBeans.get(position).getQuantity()));
viewHolder.row_item_name.setText(cartBeans.get(position).getItem_name());
viewHolder.et_quantity.addTextChangedListener(viewHolder.textWatcher);
if(isDeleteRequired){
viewHolder.deleteButton.setVisibility(View.VISIBLE);
viewHolder.et_quantity.setInputType(InputType.TYPE_CLASS_NUMBER);
viewHolder.et_quantity.setFocusableInTouchMode(true);
viewHolder.et_quantity.setCursorVisible(true);
viewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppConstants.cartBeanArrayList.remove(position);
notifyDataSetChanged();
for (int i = 0; i < AppConstants.cartBeanArrayList.size(); i++) {
// String price = AppConstants.cartBeanArrayList.get(i).getTotal_price().substring(3, AppConstants.cartBeanArrayList.get(i).getTotal_price().length());
// Log.i("total_price123",""+price);
total_price = total_price + ActivityCart.getTotal(i);
Log.i("total_price123",""+total_price);
Log.i("total_price1237",""+AppConstants.cartBeanArrayList.size());
// AppConstants.cartBeanArrayList.clear();
}
Log.i("total_price1234",""+total_price);
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(total_price));
if (AppConstants.cartBeanArrayList.size()==0)
{
ActivityCart.tv_sub_total.setText("£.0.00");
}
// AppConstants.addressBeanArrayList.setText(String.valueOf(total_price));
}
});
}else{
viewHolder.deleteButton.setVisibility(View.GONE);
}
return view;
}
class ViewHolder {
TextView row_item_name;
TextView row_price;
EditText et_quantity;
ImageView deleteButton;
public TextWatcher textWatcher;
}
public void setIsDeleteRequired(boolean isDeleteRequire){
isDeleteRequired = isDeleteRequire;
}
}
And getTotal() method coding is:
public static Double getTotal(int i) {
total =(Double.parseDouble(AppConstants.cartBeanArrayList.get(i).getTotal_price()) * AppConstants.cartBeanArrayList.get(i).getQuantity());
Log.i("totalsunder", "" +total);
return total;
}
Yes I got the answer myself.
Here my code
viewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppConstants.cartBeanArrayList.remove(position);
for (int i = 0; i < AppConstants.cartBeanArrayList.size(); i++) {
total_price = total_price + ActivityCart.getTotal(i);
}
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(total_price));
total_price =0.0;
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//removing from database
int i =impl_cart.deleteRow(data_cart.get(position).get_id());
//removing from adapter
data_cart.remove(position);
notifyDataSetChanged();
}
});
Here is my adapter code where on edit field edited am calculating the 2 other fields and displaying through TextWatcher. There are 2 issues here.
1. On scroll the values are changing to default values
2. How can I take the new values updated on click of a button
Please help...thanks.
public class ItemListAdapter extends BaseAdapter {
private ArrayList<Itemlist> mProductList,medicineList;
private LayoutInflater mInflater;
String newEditValu[];
Itemlist curProduct;
Itemlist list;
DataTranrfer df;
public ItemListAdapter(ArrayList<Itemlist> list, LayoutInflater inflater) {
mProductList = list;
mInflater = inflater;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewItem item;
final int pos=position;
medicineList=new ArrayList<Itemlist>();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_medicine_list,null);
item = new ViewItem();
item.medicineTitle = (TextView) convertView.findViewById(R.id.tvMedicineName);
item.medcineQuantity =(EditText)convertView.findViewById(R.id.etQuantity);
item.itemDaily=(TextView)convertView.findViewById(R.id.tvDailyText);
item.itemNdays=(TextView)convertView.findViewById(R.id.tvNodays);
item.itemTotal = (TextView)convertView.findViewById(R.id.tvCost);
convertView.setTag(item);
ImageButton b2 = (ImageButton) convertView.findViewById(R.id.thumbnail);
b2.setTag(position);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
mProductList.remove(pos);
ItemListAdapter.this.notifyDataSetChanged();
}
});
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
curProduct = mProductList.get(position);
item.ref=position;
item.medicineTitle.setText(curProduct.getmedicineName());
item.itemDaily.setText("Daily: " + curProduct.getMedicineDaily());
item.itemNdays.setText("Days: " + curProduct.medicineNoDays);
item.itemTotal.setText("Rs." + curProduct.getMedicineTotal());
item.medcineQuantity.setText("" + curProduct.getMedicineQuantity());
ItemListAdapter.this.notifyDataSetChanged();
item.medcineQuantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//ItemListAdapter.this.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
System.out.print("edit response" + s.toString());
Itemlist curProduct = mProductList.get(position);
if (item.medcineQuantity.getText().length() >= 0) {
double dItemcost = Double.parseDouble(curProduct.getMedicineCost());
double dItemDaily = Double.parseDouble(curProduct.getMedicineDaily());
double dItemQuantity = Double.parseDouble(item.medcineQuantity.getText().toString());
//double dItemQuantity = Double.parseDouble(myList.get(pos));
double dItemDays = (dItemQuantity / dItemDaily);
double dItemTotal = (dItemQuantity * dItemcost);
item.medcineQuantity.setText("" +myList.get(pos));
item.itemNdays.setText("Days: " + dItemDays);
item.itemTotal.setText("Rs." + dItemTotal);
list=new Itemlist();
list.setmedicineName(curProduct.getmedicineName());
list.setMedicineDaily(curProduct.getMedicineDaily());
list.setMedicineQuantity(dItemQuantity);
list.setMedicineCost("" + dItemcost);
list.setMedicineTotal(dItemTotal);
medicineList.add(list);
for(int i=0;i<medicineList.size();i++)
{
System.out.println("medicine list"+medicineList.toString());
System.out.println("medicine total at"+i+":"+medicineList.get(i).getMedicineTotal());
}
}
}
});
return convertView;
}
private class ViewItem {
TextView medicineTitle,itemDaily,itemNdays,itemTotal;
EditText medcineQuantity;
int ref;
}
}
I have created a custom ListView using ArrayAdapter. ListView's row has two views, one is the main view & other is hidden & it appears when a TextView on main view is clicked.
For showing data on rows I have a created an Object. I am facing some issues in my ListView.
This issue occurs some time. Whenever I delete an item from ListView, I can see the item is deleted from my ArrayList & then I call notifyDataSetChanged. The issue is this the ListView still shows the deleted row but its not clickable(only view is there). Only other rows are clickable which are not deleted yet. Check image 1.
I have used a flag in my Object to hide/show the hidden view. But sometimes it doesn't appear well. Check image 2
Sometimes after hiding the hidden view it still shows below the main view. Check image 3
Please help me out in this.
class ShippingAdapter extends ArrayAdapter<ShippingOption>
{
ShippingAdapter(Context context, ArrayList<ShippingOption> list)
{
super(context, R.layout.row_shipping, R.id.row_shipping_tv_product_name, list);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row = super.getView(position, convertView, parent);
ShippingViewHolder holder = (ShippingViewHolder) row.getTag();
if (holder == null)
{
holder = new ShippingViewHolder(row);
row.setTag(holder);
}
final ShippingOption shippingOption = getShippingOption(position);
holder.tvRemove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
showRemoveDialog(shippingOption.getProductId(), position);
}
});
holder.tvProductName.setText(shippingOption.getProductName());
imageLoader.DisplayImage(shippingOption.getProductImageUrl(), holder.ivProduct);
ArrayAdapter<String> adapterShippingOption = createAdapter(holder.spinnerShippingOption, shippingOption.getListShipping(), R.layout.spinner_textview_blue);
holder.spinnerShippingOption.setSelection(adapterShippingOption.getPosition(shippingOption.getSelectedOption()));
if (shippingOption.getSelectedOption().equals(Constants.PICK_UP_AT_STORE))
{
HashMap<String, Integer> mapPickupAddress = shippingOption.getMapPickupAddress();
Collection<String> collection = mapPickupAddress.keySet();
ArrayList<String> listAddress = new ArrayList<String>();
listAddress.addAll(collection);
ArrayAdapter<String> adapterAddress = createAdapter(holder.spinnerAddress, listAddress, R.layout.spinner_textview_blue_small);
holder.spinnerAddress.setSelection(adapterAddress.getPosition(shippingOption.getSelectedAddress()));
holder.relativeAddress.setVisibility(View.VISIBLE);
holder.spinnerAddress.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedAddress = parent.getItemAtPosition(position).toString();
String oldAddress = shippingOption.getSelectedAddress();
shippingOption.setSelectedAddress(selectedAddress);
if (oldAddress == null || !oldAddress.equals(selectedAddress))
notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
} else
{
holder.relativeAddress.setVisibility(View.GONE);
}
holder.spinnerShippingOption.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedOption = parent.getItemAtPosition(position).toString();
// if (!selectedOption.equals(Constants.FREE_SHIPPING))
// {
String oldOption = shippingOption.getSelectedOption();
shippingOption.setSelectedOption(selectedOption);
if (!oldOption.equals(selectedOption))
notifyDataSetChanged();
// }
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
holder.relativeLayoutGift.setVisibility(shippingOption.isGiftDetailsVisible() ? View.VISIBLE : View.GONE);
if (shippingOption.isGiftWrapAvailable())
{
imageLoader.DisplayImage(shippingOption.getGiftImageUrl(), holder.ivGift);
holder.layoutGift.setVisibility(View.VISIBLE);
ArrayList<String> listGift = new ArrayList<String>();
listGift.add("Not a Gift");
listGift.add("Yes it's a Gift $" + shippingOption.getGiftServiceCharge());
ArrayAdapter<String> adapterGift = createAdapter(holder.spinnerGift, listGift, R.layout.spinner_textview_blue);
holder.tvGiftDetails.setVisibility(shippingOption.getSelectedGiftOption().equals("Not a Gift") ? View.GONE : View.VISIBLE);
holder.spinnerGift.setSelection(adapterGift.getPosition(shippingOption.getSelectedGiftOption()));
holder.spinnerGift.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedOption = parent.getItemAtPosition(position).toString();
String oldOption = shippingOption.getSelectedGiftOption();
shippingOption.setSelectedGiftOption(selectedOption);
if (!oldOption.equals(selectedOption))
notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
holder.tvGiftDetails.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
shippingOption.setGiftDetailsVisible(true);
notifyDataSetChanged();
}
});
holder.relativeGiftDetails.setVisibility(shippingOption.isGiftDetailsVisible() ? View.VISIBLE : View.GONE);
holder.relativeLayoutGift.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
holder.btnCancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
shippingOption.setGiftDetailsVisible(false);
notifyDataSetChanged();
}
});
holder.btnClose.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
shippingOption.setGiftDetailsVisible(false);
notifyDataSetChanged();
}
});
final EditText editLocal = holder.editGiftMessage;
holder.btnApply.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
String message = editLocal.getText().toString();
shippingOption.setGiftMessageApplied(true);
shippingOption.setGiftMessage(message);
shippingOption.setGiftDetailsVisible(false);
notifyDataSetChanged();
}
});
holder.editGiftMessage.setText(shippingOption.getGiftMessage());
holder.editGiftMessage.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)
{
}
});
} else
{
holder.layoutGift.setVisibility(View.GONE);
holder.relativeGiftDetails.setVisibility(View.GONE);
}
return row;
}
}
Here i am going to demonstrate for one view tagging.
ShippingViewHolder holder;
if (holder == null)
{
holder = new ShippingViewHolder(row);
row.setTag(holder);
}
holder = (ShippingViewHolder) row.getTag();
ShippingOption shippingOption = getShippingOption(position);
holder.tvRemove.setTag(shippingOption);
holder.tvRemove.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
ShippingOption shippingOption1 =(ShippingOption) v.getTag();
int pos = getPosition(shippingOption1); // this is the function that will return you the postion of your object from your passed list of object; write it your self.
showRemoveDialog(shippingOption1.getProductId(), pos);
}
});
I am using a custom list view which contains two Buttons Yes or No. When I clicked on No button, a layout containing an edit text will be displayed. There are more than 15 items in the list view. When I tried to type and save the value in the edittext of the 1st item using TextWatcher(), then the value is save for both 5th and 1st position ie, the same value is saving in both 1st and 5th position.
The code I am using is:
holder.subQuestionAnswer.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) {
questionsModel.get(position).getQuestion_subquestion().get(0).setAnswer(holder.subQuestionAnswer.getText()
.toString());
Log.e("value", "no_active<>"+position+"<>"+questionsModel.get(position).getQuestion_subquestion().get(0).getAnswer().toString());
}
});
}
How can i avoid this?
It is because of recycling of view. Please check the following adapter. Use the logic according to your needs.
public class MultiSelectionProductAdapter extends ArrayAdapter<ProductListBean> {
private Context context;
private ArrayList<ProductListBean> productList;
private ArrayList<ProductListBean> mOriginalValues;
private LayoutInflater li;
public MultiSelectionProductAdapter(Context ctx, int simpleListItem1,
ArrayList<ProductListBean> data) {
super(ctx, simpleListItem1, data);
this.context = ctx;
this.productList = data;
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productList.size();
}
#Override
public ProductListBean getItem(int position) {
return productList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = li.inflate(R.layout.component_inventory_prod_list, null);
holder = new ViewHolder();
holder.tvProductName = (TextView) convertView.findViewById(R.id.tvProductName);
holder.tvProdShortCode = (TextView) convertView.findViewById(R.id.tvShortName);
holder.tvLastOrderedQty = (TextView) convertView.findViewById(R.id.tvLastOrderedQty);
holder.etQty = (EditText) convertView.findViewById(R.id.etQty);
holder.parentRL = (LinearLayout) convertView.findViewById(R.id.parentRL);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProductListBean tempBean = productList.get(position);
holder.etQty.setId(position);
final String productName = tempBean.getProductName();
final String productCode = tempBean.getProductCode();
final String productShortCode = tempBean.getProductShortCode();
if (mSelectedProd != null && mSelectedProd.contains(productCode)) {
final int indexOfProd = mSelectedProd.indexOf(productCode);
holder.etQty.setText(mSelectedProducts.get(indexOfProd).getEnteredQty());
}
holder.tvProductName.setText(productName);
holder.tvProdShortCode.setText(productShortCode);
holder.tvLastOrderedQty.setText(tempBean.getLastOrderedQty());
holder.etQty.setText(tempBean.getEnteredQty());
holder.parentRL.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
holder.etQty.requestFocus();
}
});
holder.etQty.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) {
final int pos = holder.etQty.getId();
final String qty = holder.etQty.getText().toString();
if (qty.length() > 0) {
if (String.valueOf(qty.charAt(0)).equals("0")) {
holder.etQty.setError("Invalid Quantity");
holder.etQty.setText("");
} else {
productList.get(pos).setEnteredQty(holder.etQty.getText().toString());
}
} else {
productList.get(pos).setEnteredQty("");
}
}
});
return convertView;
}
static class ViewHolder {
TextView tvProductName, tvProdShortCode, tvLastOrderedQty;
EditText etQty;
LinearLayout parentRL;
}