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;
}
Related
I'm creating an android app, in which I'm using recyclerView and the row of recyclerView is having editText.
This is my ReadingAdapter class
public class ReadingAdapter extends RecyclerView.Adapter<ReadingAdapter.ViewHolder> implements AdapterView.OnItemSelectedListener {
Context context;
String valOpenReading, valClosReading, valConsumption;
private List<ReadingData> readingList;
static String[] arrValOpenRead, arrValClosRead, arrValConsumption;
public ReadingAdapter(Context context, List<ReadingData> readingList) {
this.context = context;
this.readingList = readingList;
arrValOpenRead = new String[readingList.size()];
arrValClosRead = new String[readingList.size()];
arrValConsumption = new String[readingList.size()];
}
#Override
public ReadingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reading_sheet_layout, parent, false);
return new ReadingAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final ReadingAdapter.ViewHolder holder, final int position) {
ReadingData tempData = readingList.get(position);
holder.pdtName.setText(tempData.pdtName);
holder.keyId.setText("Key "+tempData.keyId);
holder.etClosRead.addTextChangedListener(new TextWatcher() {
boolean ignore = false;
#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 (ignore)
return;
ignore = true;
valOpenReading = holder.etOpenRead.getText().toString();
arrValOpenRead[position] = valOpenReading;
valClosReading = s.toString().equals("") ? "0": s.toString();
arrValClosRead[position] = valClosReading;
if (!valOpenReading.equals("")) {
if (Integer.parseInt(valClosReading) < Integer.parseInt(valOpenReading)) {
Toast.makeText(context, "Check once! closing reading should be more than opening reading!", Toast.LENGTH_LONG).show();
valConsumption = "0";
holder.consumption.setText("");
} else {
valConsumption = (Integer.parseInt(valClosReading) - Integer.parseInt(valOpenReading))+"";
arrValConsumption[position] = valConsumption;
holder.consumption.setText(valConsumption);
}
} else
Toast.makeText(context, "Please fill the opening reading!", Toast.LENGTH_SHORT).show();
ignore = false;
}
});
}
#Override
public int getItemCount() {
return readingList.size();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView pdtName, keyId, consumption;
EditText etOpenRead, etClosRead;
public ViewHolder(View view) {
super(view);
pdtName = (TextView)view.findViewById(R.id.txt_list_pdt_supp);
keyId = (TextView)view.findViewById(R.id.key_set);
etOpenRead = (EditText)view.findViewById(R.id.open_val_set);
etClosRead = (EditText)view.findViewById(R.id.clos_val_set);
consumption = (TextView)view.findViewById(R.id.consumption_val);
}
}
}
This is my ReadingData.java
public class ReadingData {
String pdtName, keyId, openReading, closReading, consumption;
public ReadingData(String pdtName, String keyId) {
this.pdtName = pdtName;
this.keyId = keyId;
}
}
Here, if I enter value in the starting items of the recyclerView then as I scroll up the items to the bottom of the list, the last item will have that value.
Please ignore the quality of image as we can't upload above of 2MiB of snap.
Here the views are recycled as the list is scrolled. How to prevent the copying values to the other item in the list.
And that Toast is also repeated several times. How to stop this.
update:
By the suggetion of LQ Gioan through the SO question How ListView's recycling mechanism works , I got the logic how ListView actually works with recycling of views.
But I'm not sure whether the recyclerView also works same.
But here in my case, how can I implement this process. pls someone help me here.
RecyclerView reuse views, in fact it only generate the as many as views that is visible on the screen. so it's expected if you can see a value you set for other rows
The solution would be set all attributes of the view that you are changing to default or whatever the row should present from your data set
So put addTextChangedListener insode ViewHolder constructor(you can get position by calling getAdapterPosition()) for better performance and set the editText value inside onBindViewHolder method from your data set
Your Activity Code:
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setItemsCanFocus(true);
Adapter adapter = new Adapter (YourActivity.this, YourArrayList);
listview .setAdapter(adapter);
Adapter class
public class Adapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
Activity act;
String[] temp;
public Adapter(Context context, ArrayList<String> list) {
mContext = context;
inflater = LayoutInflater.from(mContext);
act = (Activity) context;
//-------Temp String Array-------\\
temp = new String[this.count];
for (int i = 0; i < this.count; i++) {
temp[i] = list.get(i);
}
//---------------------------\\
}
public class ViewHolder {
TextView optionTitle;
EditText optionText;
int ref;
}
#Override
public int getCount() {
return list.size;
}
#Override
public Object getItem(int position) {
return temp[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_add_ques_options_mcq, null);
holder.optionTitle = (TextView) view.findViewById(R.id.add_ques_opts_count_mcq_tv);
holder.optionText = (EditText) view.findViewById(R.id.add_ques_opts_title_mcq_et);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ref = position;
holder.optionTitle.setText(getCharForNumber(position) + ":");
holder.optionText.setText(temp[position]);
holder.optionText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
temp[holder.ref] = arg0.toString().trim();
}
});
return view;
}
public void getList() {
StaticValues.arrayListOptions = new ArrayList<String>(Arrays.asList(temp));
StaticValues.arrayListOptionsCount = new ArrayList<String>();
for (int i = 0; i < count; i++) {
StaticValues.arrayListOptionsCount.add(String.valueOf(i+1));
Log.e("err_al", StaticValues.arrayListOptions.get(i));
Log.e("err_al", StaticValues.arrayListOptionsCount.get(i));
}
}
private String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
if (i > 25) {
return null;
}
return Character.toString(alphabet[i]);
}}
hello every one i am really struck from last 3 days in a very tiny place i have 3 custom listview in my application what does my application is when i check value in one listvew and then scoll other list view the data of first edit box automatically pass to other and i dont want that . . my first adapter
public class Doneyesadapter extends BaseAdapter {
private List<ApplicationInfo> appInfoList;
private LayoutInflater mInflater;
private PackageManager pm;
ArrayList<Boolean> positionArray;
private Context ctx;
int[] visiblePosArray;
private volatile int positionCheck;
String[] strItecode=null;
String[] strItem;
String[] strQuantity,text;
int temp;
private int editingPosition = 0;
ArrayList<String> listItem;
ArrayList<String> listAddress;
ArrayList<String> quantity;
ArrayList<String> idlist;
public static ArrayList<String> ItemID_list=new ArrayList<String>();
public static ArrayList<String> StockCode_list=new ArrayList<String>();
public static ArrayList<String> Description_list=new ArrayList<String>();
public static ArrayList<String> Quantity_list=new ArrayList<String>();
Context mContext;
ArrayList<String> dates;
//constructor
public Doneyesadapter(Context mContext, ArrayList<String> listItem, ArrayList<String> listAddress,ArrayList<String> quantity
,ArrayList<String> idlist ) {
this.mContext = mContext;
this.listItem = listItem;
this.listAddress = listAddress;
this.quantity = quantity;
this.idlist = idlist;
text= new String[idlist.size()];
pm = mContext.getPackageManager();
positionArray = new ArrayList<Boolean>(listItem.size());
for(int i =0;i<listItem.size();i++){
positionArray.add(false);
}
//this.dates=date;
}
private TextWatcher watcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
text[editingPosition] = s.toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void afterTextChanged(Editable s) { }
};
public int getCount() {
return listItem.size();
}
public void cleardata(){
listAddress.clear();
listItem.clear();
}
public Object getItem(int arg0) {
return null;
}
public String getName(int pos){
int name =pos;
String ll = listAddress.get(name);
return ll;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View arg1, ViewGroup viewGroup) {
final ViewHolder1 holder;
temp=position;
if (arg1 == null) {
holder = new ViewHolder1();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arg1 = inflater.inflate(R.layout.stocklistcustom, viewGroup, false);
holder.checkbox1 = (CheckBox) arg1.findViewById(R.id.checkbox1);
holder.Des = (TextView) arg1.findViewById(R.id.description1);
holder.stockid = (TextView) arg1.findViewById(R.id.stockid1);
holder.done = (EditText) arg1.findViewById(R.id.quantity1);
holder.stockid.setText(listItem.get(position));
holder.Des.setText(listAddress.get(position));
holder.done.setText(quantity.get(position));
arg1.setTag(holder);
} else {
holder = (ViewHolder1) arg1.getTag();
}
holder.checkbox1.setOnCheckedChangeListener(null);
holder.checkbox1.setFocusable(false);
// holder.checkbox1.setImageDrawable(appInfoList.get(position).loadIcon(pm));
holder.checkbox1.setChecked(positionArray.get(position));
// holder.checkbox1.setText(appInfoList.get(position).loadLabel(pm));
holder.checkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int i = 0;
// Toast.makeText(mContext, "here is commom"+buttonView, Toast.LENGTH_SHORT).show();
if (holder.checkbox1.isChecked()) {
quantity.set(position,holder.done.getText().toString());
positionArray.set(position, true);
String id, qu, des, stc;
id = idlist.get(position);
qu = quantity.get(position);
des = listAddress.get(position);
stc = listItem.get(position);
ItemID_list.add(i, id);
StockCode_list.add(i, stc);
Description_list.add(des);
Quantity_list.add(i,text[temp]);
quantity.set(position,holder.done.getText().toString());
holder.done.setText(quantity.get(position));
i++;
} else {
positionArray.set(position, false);
ItemID_list.remove(i);
StockCode_list.remove(i);
Description_list.remove(i);
Quantity_list.remove(i);
holder.done.setText(quantity.get(position));
i--;
}
}
});
holder.done.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
text[temp] = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text[temp] = s.toString();
}
});
holder.done.setText(text[temp]);
//date.setText(dates);
holder.stockid.setText(listItem.get(position));
holder.Des.setText(listAddress.get(position));
holder.done.setText(quantity.get(position));
return arg1;
}
private class ViewHolder1{
CheckBox checkbox1;
TextView Des;
TextView stockid;
EditText done;
}
}
my second adapter
public Doneyesadapter2(Context mContext, ArrayList<String> listItem, ArrayList<String> listAddress,ArrayList<String> quantity
,ArrayList<String> idlist ) {
this.mContext = mContext;
this.listItem = listItem;
this.listAddress = listAddress;
this.quantitys = quantity;
this.idlist = idlist;
text= new String[idlist.size()];
pm = mContext.getPackageManager();
positionArray = new ArrayList<Boolean>(listItem.size());
for(int i =0;i<listItem.size();i++){
positionArray.add(false);
}
//this.dates=date;
}
private TextWatcher watcher = new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
text[editingPosition] = s.toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void afterTextChanged(Editable s) { }
};
public int getCount() {
return listItem.size();
}
public void cleardata(){
listAddress.clear();
listItem.clear();
}
public Object getItem(int arg0) {
return null;
}
public String getName(int pos){
int name =pos;
String ll = listAddress.get(name);
return ll;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View arg11, ViewGroup viewGroup) {
final ViewHolders2 holder;
int a=3;
Log.e("second getview called", String.valueOf(a));
temp=position;
if (arg11 == null) {
holder = new ViewHolders2();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
arg11 = inflater.inflate(R.layout.stocklistcustom2, viewGroup, false);
holder.checkbox1 = (CheckBox) arg11.findViewById(R.id.checkbox2);
holder.Des = (TextView) arg11.findViewById(R.id.description2);
holder.stockid = (TextView) arg11.findViewById(R.id.stockid2);
holder.done = (EditText) arg11.findViewById(R.id.quantity2);
holder.stockid.setText(listItem.get(position));
holder.Des.setText(listAddress.get(position));
holder.done.setText(quantitys.get(position));
arg11.setTag(holder);
}
else {
holder = (ViewHolders2) arg11.getTag();
}
holder.checkbox1.setOnCheckedChangeListener(null);
holder.checkbox1.setFocusable(false);
// holder.checkbox1.setImageDrawable(appInfoList.get(position).loadIcon(pm));
holder.checkbox1.setChecked(positionArray.get(position));
holder.checkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int i = 0;
if (holder.checkbox1.isChecked()) {
quantitys.set(position,holder.done.getText().toString());
positionArray.set(position, true);
String id, qu, des, stc;
id = idlist.get(position);
qu = quantitys.get(position);
des = listAddress.get(position);
stc = listItem.get(position);
ItemID_list2.add(i, id);
StockCode_list2.add(i, stc);
Description_list2.add(des);
//Quantity_list2.add(, holder.done.getText().toString());
Quantity_list2.add(i,holder.done.getText().toString());
i++;
general=i;
} else {
positionArray.set(position, false);
ItemID_list2.remove(i);
StockCode_list2.remove(i);
Description_list2.remove(i);
Quantity_list2.remove(i);
i--;
general=i;
}
}
});
holder.done.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
text[temp] = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
text[temp] = s.toString();
}
});
holder.done.setText(text[temp]);
holder.stockid.setText(listItem.get(position));
holder.Des.setText(listAddress.get(position));
holder.done.setText(quantitys.get(position));
//date.setText(dates);
return arg11;
}
private class ViewHolders2{
CheckBox checkbox1;
TextView Des;
TextView stockid;
EditText done;
}
}
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 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
I have a listview and in each row there are some edittext. On loading for the firsttime I have assigned values to every edittexts and are editable. I can edit the values in that edittext. My problem is that after changing the position of that rows ie: after scrolling I am getting the initial values in that edittexts, not the editted values. I am working on this for the past 6 hours. Any one please help me.
Here is my adapter class
public class ListAdapter_baradmin extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
public ArrayList myItems = new ArrayList();
public static String[] str_Id = new String[datalength];
public static String[] str_Idoriginal = new String[datalength];
public static String[] str_Desc = new String[datalength];
public static String[] str_UOM = new String[datalength];
public static String[] str_Parlevel = new String[datalength];
public static String[] str_Openingstock = new String[datalength];
public static String[] str_Reg = new String[datalength];
public static String[] str_Intertransfer= new String[datalength];
public static String[] str_Closingstock = new String[datalength];
public static String[] str_Remark = new String[datalength];
SeparatedListAdapter separatedListAdapter;
ArrayList<String> Data_id = new ArrayList<String>();
ArrayList<String> Data_name = new ArrayList<String>();
ArrayList<String> Data_parlevel = new ArrayList<String>();
ArrayList<String> Data_uom = new ArrayList<String>();
ArrayList<String> Data_Openingstock = new ArrayList<String>();
ArrayList<String> Data_Reg = new ArrayList<String>();
ArrayList<String> Data_Intertransfer= new ArrayList<String>();
ArrayList<String> Data_Closingstock = new ArrayList<String>();
ArrayList<String> Data_Remark = new ArrayList<String>();
public ListAdapter_baradmin(Context context
,ArrayList<String> Items_id
,ArrayList<String> Items_desc
,ArrayList<String> Items_perunitcost
,ArrayList<String> Items_uom
,ArrayList<String> Items_idoriginal
,ArrayList<String> Items_os
,ArrayList<String> Items_intertransfer
,ArrayList<String> Items_cs
,ArrayList<String> Items_remark
,ArrayList<String> Items_reg) {
ctx = context;
Data_id .addAll(Items_id);
Data_name .addAll(Items_desc);
Data_parlevel .addAll(Items_perunitcost);
Data_uom .addAll(Items_uom);
Data_Openingstock .addAll(Items_os);
Data_Reg .addAll(Items_reg);
Data_Intertransfer .addAll(Items_intertransfer);
Data_Closingstock .addAll(Items_cs);
Data_Remark .addAll(Items_remark);
for(int i=0;i<Items_id.size();i++){
str_Id[i] = Items_id.get(i);
str_Idoriginal[i] = Items_idoriginal.get(i);
str_Desc[i] = Items_desc.get(i);
str_UOM[i] = Items_uom.get(i);
str_Parlevel[i] = Items_perunitcost.get(i);
str_Openingstock[i] = Items_os.get(i);
str_Reg[i] = Items_reg.get(i);
str_Intertransfer[i] = Items_intertransfer.get(i);
str_Closingstock[i] = Items_cs.get(i);
str_Remark[i] = Items_remark.get(i);
//System.out.println("str_Idoriginal "+str_Idoriginal[i]);
}
notifyDataSetChanged();
}
#Override
public int getCount() {
return Data_id.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
//convertView = (View)lInflater.inflate(R.layout.baradmin_row, null);
convertView = (View) lInflater.inflate(R.layout.baradmin_row, parent, false);
//holder = new ViewHolder();
holder.editText_id = (EditText) convertView.findViewById(R.id.edittext_slno_baradmin);
holder.editText_desc = (EditText) convertView.findViewById(R.id.edittext_desc_baradmin);
holder.editText_uom = (EditText) convertView.findViewById(R.id.edittext_uom_baradmin);
holder.editText_parlevel = (EditText) convertView.findViewById(R.id.edittext_parlevel_baradmin);
holder.edittext_openingstock_baradmin = (EditText) convertView.findViewById(R.id.edittext_openingstock_baradmin);
holder.edittext_reg_baradmin = (EditText) convertView.findViewById(R.id.edittext_reg_baradmin);
holder.edittext_intertransfer_baradmin = (EditText) convertView.findViewById(R.id.edittext_intertransfer_baradmin);
holder.edittext_closingstock_baradmin = (EditText) convertView.findViewById(R.id.edittext_closingstock_baradmin);
holder.edittext_remark_baradmin = (EditText) convertView.findViewById(R.id.edittext_remark_baradmin);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.editText_id .setText(position+1+"");
holder.editText_desc .setText(Data_name.get(position));
holder.editText_uom .setText(Data_uom.get(position));
holder.editText_parlevel .setText(Data_parlevel.get(position));
holder.edittext_reg_baradmin .setText(Data_Reg.get(position));
holder.edittext_openingstock_baradmin .setText(Data_Openingstock.get(position));
holder.edittext_intertransfer_baradmin .setText(Data_Intertransfer.get(position));
holder.edittext_closingstock_baradmin .setText(Data_Closingstock.get(position));
holder.edittext_remark_baradmin .setText(Data_Remark.get(position));
setNameTextChangeListener(holder);
holder.edittext_openingstock_baradmin.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
str_Openingstock[position] = holder.edittext_openingstock_baradmin.getText().toString();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
return convertView;
}
class ViewHolder {
EditText editText_id, editText_desc, editText_uom, editText_parlevel,
edittext_openingstock_baradmin, edittext_reg_baradmin, edittext_intertransfer_baradmin,
edittext_closingstock_baradmin, edittext_remark_baradmin;
}
private void setNameTextChangeListener(final ViewHolder holder) {
holder.edittext_openingstock_baradmin.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("s.toString() "+s.toString());
//holder.edittext_openingstock_baradmin.setText(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
class ListItem {
String caption;
}
}
You have to update s.toString() value in your array.
Data_Openingstock.set(position, s.toString());
setNameTextChangeListener(Holder holder, int position);
private void setNameTextChangeListener(final ViewHolder holder, final int position) {
holder.edittext_openingstock_baradmin.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//do null check first before converting to string
if(s.length() > 0)
{
System.out.println("s.toString() "+s.toString());
Data_Openingstock.set(position, s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
You need to use Viewholder class and initialize edittext every time while inflating list item layout in getview of listview.
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.element_in_game, null);
holder.scoreToUpdate = (EditText) convertView
.findViewById(R.id.elementUpdateScore);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
initScoresToUpdateEditTexts(holder.scoreToUpdate, hint);
holder.scoreToUpdate.setText(scoresToUpdate[tmp_position]);
holder.scoreToUpdate.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
scoresToUpdate[tmp_position] = s.toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
return convertView;
}
See these answers also
Android :EditText loses content on scroll in ListView?
EditText Content Changes on ListView Scroll
I resolved this issue by implementing following code.
put following code in getview method of adapter class
viewHolder.invAmt.setTag(position);//set tag
holder.edittext_openingstock_baradmin.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) {
int pos = (Integer) holder.edittext_openingstock_baradmin.getTag();
scoresToUpdate[pos] = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
try it.100 % working code