How to store and retrieve editText from a listview that have 2 editText on each row?
With this code, when I write something to one editText, it copy the value to all others.
public class CheckoutAdapter extends BaseAdapter{
private Context mContext;
private List<JsonObject> mObjs;
private ViewHolder holder;
private SessionManager session;
private float Value = 0;
private int tax = 0;
private float Total = 0;
private int viewID = 0;
private EnhancedListView listview;
private ImageLoader imageLoader = ImageLoader.getInstance();
static DisplayImageOptions options;
private ArrayList<String> arrayFirstName = new ArrayList<String>();
private ArrayList<String> arrayLastName = new ArrayList<String>();
public CheckoutAdapter(Context context, List<JsonObject> objs, EnhancedListView mListView) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mObjs = objs;
this.listview = mListView;
for (int i = 0; i < mObjs.size(); i++) {
arrayFirstName.add("");
arrayLastName.add("");
}
}
//Classe ViewHolder
public final class ViewHolder {
public TextView ticketValue;
public TextView ticketItem;
public TextView ticketOpcao;
public TextView ticketTax;
public TextView ticketTitle;
public TextView ticketDate;
public TextView ticketFullName;
public EditText ticketFirstName;
public EditText ticketLastName;
public ImageView ticketImageThumb;
int position;
}
public void remove(int position) {
mObjs.remove(position);
}
public void insert(int position, JsonObject item) {
mObjs.add(position, item);
}
#Override
//Contar a quntidade de linhas.
public int getCount() {
// TODO Auto-generated method stub
return mObjs.size();
}
#Override
//Pegar o item conforme a posição.
public Object getItem(int position) {
// TODO Auto-generated method stub
return mObjs.get(position);
}
#Override
//ID do item (refere-se a posição em que ele se encontra).
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;
//Se não houver nenhuma View, uma nova view é criada.
if(convertView==null)
{
vi = LayoutInflater.from(mContext).inflate(R.layout.row_checkout, null);
Typeface font = Typeface.createFromAsset(mContext.getAssets(), "fonts/Oswald-Bold.otf");
final View origView = vi;
vi.findViewById(R.id.action_delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listview.delete(((ViewHolder)origView.getTag()).position);
}
});
holder = new ViewHolder();
holder.ticketItem = (TextView)vi.findViewById(R.id.tvItem);
holder.ticketOpcao = (TextView)vi.findViewById(R.id.tvOpcao);
holder.ticketTax = (TextView)vi.findViewById(R.id.tvTaxa);
holder.ticketValue = (TextView)vi.findViewById(R.id.tvValue);
holder.ticketValue.setTypeface(font);
holder.ticketTitle = (TextView)vi.findViewById(R.id.tvTitle);
holder.ticketTitle.setTypeface(font);
holder.ticketDate = (TextView)vi.findViewById(R.id.tvDate);
holder.ticketDate.setTypeface(font);
holder.ticketFullName = (TextView)vi.findViewById(R.id.tvFullName);
holder.ticketFullName.setTypeface(font);
holder.ticketFirstName = (EditText)vi.findViewById(R.id.etFirstName);
holder.ticketLastName = (EditText)vi.findViewById(R.id.etLastName);
holder.ticketImageThumb = (ImageView)vi.findViewById(R.id.imgFlyerSub);
holder.position = position;
holder.ticketFirstName.addTextChangedListener(FirstNameChangedListener(position));
holder.ticketLastName.addTextChangedListener(LastNameChangedListener(position));
holder.ticketFirstName.setOnFocusChangeListener(FirstNameFocusChangeListener(position));
holder.ticketLastName.setOnFocusChangeListener(LastNameFocusChangeListener(position));
vi.setTag(holder);
//Caso já exista uma view o objeto holder recebe o getTag da View vi.
} else {
holder = (ViewHolder)vi.getTag();
}
holder.ticketItem.setText(mObjs.get(position).getAsJsonObject().get(Constants.JSON.JSON_ITEM).getAsString());
holder.ticketOpcao.setText(mObjs.get(position).getAsJsonObject().get(Constants.JSON.JSON_OPCAO).getAsString());
holder.ticketTax.setText("Taxa de serviço:" + mObjs.get(position).getAsJsonObject().get(Constants.JSON.JSON_TAX).getAsString() + "%");
holder.ticketValue.setText("R$" + String.valueOf(mObjs.get(position).getAsJsonObject().get(Constants.JSON.JSON_VALUE).getAsInt()) + ",00");
holder.ticketDate.setText(mObjs.get(position).getAsJsonObject().get(Constants.KEY.KEY_EVENTDATE).getAsString());
holder.ticketTitle.setText(mObjs.get(position).getAsJsonObject().get(Constants.JSON.JSON_EVENTTITLE).getAsString());
holder.ticketFirstName.setText(arrayFirstName.get(holder.position));
holder.ticketLastName.setText(arrayLastName.get(holder.position));
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ico_load_imagem)
.cacheInMemory().cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(5))
.build();
imageLoader.displayImage(mObjs.get(position).getAsJsonObject().get("thumbPrincipal").getAsString(), holder.ticketImageThumb, options);
return vi;
}
private View.OnFocusChangeListener LastNameFocusChangeListener(final int position) {
return new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
viewID = holder.position;
}
}
};
}
private View.OnFocusChangeListener FirstNameFocusChangeListener(final int position) {
return new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
viewID = holder.position;
}
}
};
}
private TextWatcher FirstNameChangedListener(final int position) {
return 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) {
String itemName = s.toString();
arrayFirstName.add(viewID, itemName);
}
};
}
private TextWatcher LastNameChangedListener(final int position) {
return 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) {
String itemName = s.toString();
arrayLastName.add(viewID, itemName);
}
};
}
}
EDIT: Removed setId and JSON.
Your holder is a member of your class, it's wrong.
Remove it from this place. Every line of your listview has its own holder.
This holder is "sticked" to the view by the setTag method.
In listeners that used holder, you have to get the holder from the view that send the event.
For this, the following code should work:
private View.OnFocusChangeListener FirstNameFocusChangeListener(final int position) {
return new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
ViewHolder holder = (ViewHolder ) v.getTag();
viewID = holder.position;
}
}
};
}
Related
I'm not expert in android listview and Edittext. However, I am stuck with some annoying problem regarding this issue. I am fetching values in listview without any problem but when I input something in Edittext and scroll down the value of EditText changes it's position. Here is my code.
//product class
public class products {
public String prod_sl;
public String prod_code;
public String product_name;
public String product_desc;
public String prod_qnty;
public String prod_uom;
public String prod_price;
boolean ShowName;
public products(String psl, String pcode,String Name, String Desc, String UOM) {
this.prod_sl = psl;
prod_code = pcode;
prod_qnty="";
prod_price ="";
product_name=Name;
product_desc=Desc;
prod_uom =UOM;
}
/* public boolean isShowName() {
return ShowName;
}
public void setShowName(boolean showName) {
ShowName = showName;
}*/
//sl
public String getSl() { return prod_sl; }
public void setSl(String psl) { this.prod_sl = psl; }
//product code
public String getCode() { return prod_code; }
public void setCode(String pcode) { this.prod_code = pcode; }
//product Name
public String getName() { return product_name; }
public void setName(String product_name) { this.product_name = product_name; }
//product desc
public String getDesc() { return product_desc; }
public void setDesc(String product_desc) { this.product_desc = product_desc; }
//product UOM
public String getUom() { return prod_uom; }
public void setUom(String prod_uom) { this.prod_uom = prod_uom; }
// product quantity
public String getQnty() {
return prod_qnty; }
public void setQnty(String prod_qnty) {
this.prod_qnty = prod_qnty; }
//product price
public String getPrice() {
return prod_price; }
public void setPrice(String prod_price) {
this.prod_price = prod_price; }
}
And here is the adapter class
public class ListViewAdapter extends ArrayAdapter<products> {
Context mContext;
View v;
private String[] arrTemp;
LayoutInflater inflater;
ArrayList<products> arrayproducts;
public String[] scoresToUpdate=new String[1000];
//public String Array scoresToUpdate =scoresToUpdate[];
public static EditText edit_qnty,prod_price;
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
public ListViewAdapter(Context context, int resource, ArrayList<products> arrayproducts) {
super(context, resource);
this.mContext = context;
this.arrayproducts = arrayproducts;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
final int pos=position;
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_adapter_view, null);
holder = new ViewHolder();
holder.prod_sl = (TextView) convertView.findViewById(R.id.prod_sl);
holder.prod_code = (TextView) convertView.findViewById(R.id.prod_code);
holder.txtTitle = (TextView) convertView.findViewById(R.id.adapter_text_title);
holder.txtDescription = (TextView) convertView.findViewById(R.id.adapter_text_description);
holder.prod_uom = (TextView) convertView.findViewById(R.id.prod_uom);
holder.prod_qnty = (EditText) convertView.findViewById(R.id.prod_qnty);
holder.prod_price = (EditText) convertView.findViewById(R.id.prod_price);
// edit_qnty = (EditText) convertView.findViewById(R.id.prod_qnty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// holder.prod_qnty.setText(scoresToUpdate[pos]);
}
holder.ref = position;
products prod = arrayproducts.get(position);
holder.prod_sl.setText("" + position);
holder.prod_code.setText(prod.getCode());
holder.txtTitle.setText(prod.getName());
holder.txtDescription.setText(prod.getDesc());
holder.prod_uom.setText(prod.getUom());
Log.e("row values",""+position+"\t-"+prod.getCode()+""+prod.getName()+""+prod.getDesc()+""+prod.getUom());
// holder.prod_qnty.setText(arrTemp[position]);
holder.prod_qnty.setText(scoresToUpdate[position]);
holder.prod_qnty.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
arrayproducts.get(pos).setQnty(holder.prod_qnty.getText().toString().trim());
myList.put(pos,arg0.toString().trim());
if (!arg0.equals("0")){
scoresToUpdate[pos] = arg0.toString();
Log.e("On text Change","Pos"+pos+"\tqnty:"+holder.prod_qnty.getText().toString().trim()+"\t Args: "+arg0.toString());
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Log.e("After Text change","Pos"+holder.ref+"\tqnty:"+holder.prod_qnty.getText().toString().trim());
// arrTemp[holder.ref] = arg0.toString();
}
});
//holder.prod_qnty.setText(myList.get(position));
holder.prod_qnty.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("Current Qnty",edit_qnty.getText().toString().trim());
if(holder.prod_qnty.getText().toString().trim().equals("0")){
holder.prod_qnty.setText("");
}
String inttext = (""+holder.prod_qnty.getText().toString().trim());
if (!inttext.equals("0")){
holder.prod_price.setText("");
}
return false;
//return true;
}
});
//Using setOnclickListener not setOnCheckedChangeListener
//we need to update adapter once we finish with editing
/* holder.prod_qnty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int pos = v.getId();
final EditText Qnty = (EditText) v;
Log.e("Qnty For the positon","POS: "+pos+"\tQnty: "+Qnty.getText().toString().trim());
arrayproducts.get(pos).setQnty(Qnty.getText().toString().trim());
//holder.prod_qnty.setText(Caption.getText().toString().trim());
}
}
});*/
/* holder.prod_price.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayproducts.get(position).setPrice(Caption.getText().toString().trim());
}
}
});
*/
return convertView;
}
catch(Exception e){
Toast.makeText(mContext, "!!!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
Log.e("Exception:",""+e.toString());
}
return convertView;
}
/* #Override
public int getCount() {
return arrayproducts.size();
}*/
#Override
public int getCount() {
// TODO Auto-generated method stub
if(arrayproducts != null && arrayproducts.size() != 0){
return arrayproducts.size();
}
return 0;
}
/*#Override
public Objects getItem(int position) {
// TODO Auto-generated method stub
return arrayproducts[position];
}*/
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void getQnty(){
if(edit_qnty.getText().toString().trim().equals("0"))
edit_qnty.setText("");
}
static class ViewHolder {
TextView prod_sl;
TextView prod_code;
TextView txtTitle;
TextView txtDescription;
TextView prod_uom;
EditText prod_qnty,prod_price;
TextWatcher qtyWatcher;
TextWatcher priceWatcher;
int ref;
}
}
Please help me, With regards
This works for me !
if (holder.qtyWatcher != null) {
holder.txtFourth.removeTextChangedListener(holder.qtyWatcher);
}
// Create the TextWatcher corresponding to this row
holder.qtyWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if(s.toString().equals("")||s.toString().equals("0")){
arrayproducts.get(position).setQnty("0");
}
else{
arrayproducts.get(position).setQnty(s.toString());
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
};
not sure that listview and recycleview can be used like this as they involve a recycling mechanism to reuse created views and rebind data from arrays or cursors as users scroll down/up to see more data. in other words, the row views created are with limited number to only fill the screen (with few extra from both sides) and they are recycled and reused to show data, if you insert a price or quantity for one product line, how the recycling process will rebind to show same data you inserted or show it on same position, I doubt this is possible.
I suggest that you restructure your application on parent/child base. show on list parent data, for example fixed product data, when users click one product line another screen opens so users insert new data, for example the price for that particular product line, the layout of your child screen will contains the edittext and any other data input views, in such case you need to integrate SQLite database so that you persist the new data provided by users.
hope this may provide you with some useful ideas to help you achieve your target.
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 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;
}
I have the following custom base adapter. I have a listview with a edittext on each item. I want to save that data as soon as the user leaves the edittext, but what happens now is that each time the user types in 1 char, the setOnFocusChangeListener triggers. I really don't know why this is happening.
My custom base adapter class
public class ChecklistBaseAdapter extends BaseAdapter {
private static ArrayList<Checklist> searchArrayList;
Context currentcontext;
DatabaseHandler db;
private LayoutInflater mInflater;
public ChecklistBaseAdapter(Context context, ArrayList<Checklist> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
currentcontext = context;
db = new DatabaseHandler(currentcontext);
}
public int getCount() {
return searchArrayList.size();
}
public void remove(int position) {
searchArrayList.remove(position);
notifyDataSetChanged();
}
public void removeAll() {
searchArrayList.clear();
notifyDataSetChanged();
}
public void add(Checklist checklist) {
searchArrayList.add(checklist);
notifyDataSetChanged();
}
public void notifyChange() {
notifyDataSetChanged();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.checklistitem, null);
holder = new ViewHolder();
holder.cbStatus = (CheckBox) convertView
.findViewById(R.id.checkbox);
holder.etName = (EditText) convertView.findViewById(R.id.editname);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Checklist checklist = (Checklist) getItem(position);
holder.etName.setText(checklist.getName());
holder.etName.setId(position);
if (searchArrayList.get(position).getStatus().equals("F")) {
holder.cbStatus.setChecked(false);
} else {
holder.cbStatus.setChecked(true);
}
holder.etName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
int myint = v.getId();
searchArrayList.get(myint)._name = v.getText().toString();
return true;
}
return false;
}
});
holder.etName
.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
String input;
EditText editText;
if (!hasFocus) {
Log.e("test", "test123");
int myint = v.getId();
editText = (EditText) v;
input = editText.getText().toString();
searchArrayList.get(myint)._name = input;
}
}
});
holder.cbStatus
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String name = holder.etName.getText().toString().trim();
if (isChecked) {
for (int x = 0; x < searchArrayList.size(); x++) {
Checklist checklist = new Checklist();
checklist = searchArrayList.get(x);
if (name.equals(checklist.getName())) {
checklist.setStatus("T");
db.updateCheckList(checklist);
searchArrayList.set(x, checklist);
}
}
} else {
for (int x = 0; x < searchArrayList.size(); x++) {
Checklist checklist = new Checklist();
checklist = searchArrayList.get(x);
if (name.equals(checklist.getName())) {
checklist.setStatus("F");
searchArrayList.set(x, checklist);
db.updateCheckList(checklist);
}
}
}
}
});
return convertView;
}
static class ViewHolder {
CheckBox cbStatus;
EditText etName;
}
}
Try using the addTextChangedListener() method
holder.etName.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) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String input;
EditText editText;
Log.e("test", "test123");
int myint = v.getId();
editText = (EditText)v;
input = editText.getText().toString();
searchArrayList.get(myint)._name = input;
});
Hope It will Help you.
I have a ListView with a BaseAdapter , I want to make a filter after the filed tipdoc,and my code doesn't work ,I mean nothing is heapen when start to write in the EditText and I can't find why,This is my code:
listView = (ListView) findViewById(android.R.id.list);
adapter = new ImageAndTextAdapter(Documente.this, R.layout.list_row,nume,tipdoc,formatdoc);
listView.setAdapter(adapter);
edt = (EditText) findViewById(R.id.search_box);
edt.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ArrayList<String> nume_sort = new ArrayList<String>();
ArrayList<String> tipdoc_sort = new ArrayList<String>();
ArrayList<String> formatdoc_sort = new ArrayList<String>();
int textlength = edt.getText().length();
nume_sort.clear();
tipdoc_sort.clear();
formatdoc_sort.clear();
for (int i = 0; i < tipdoc.size(); i++)
{
if (textlength <= tipdoc.get(i).length())
{
if (edt.getText().toString().equalsIgnoreCase((String) tipdoc.get(i).subSequence(0, textlength)))
{
tipdoc_sort.add(tipdoc.get(i));
}
}
}
listView.setAdapter(new ImageAndTextAdapter
(Documente.this, R.layout.list_row,nume_sort,tipdoc_sort,formatdoc_sort));
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private class ImageAndTextAdapter extends BaseAdapter{
private Context adContext;
public int getCount() {
return nume.size();
}
public ImageAndTextAdapter(Context context,int layout,ArrayList<String> nume,ArrayList<String> tipdoc,ArrayList<String> formatdoc)
{
super();
this.adContext = context;
}
public View getView(int pos, View inView, ViewGroup parent){
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater)adContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_row, null);
}
String num = String.format(nume.get(pos));
((TextView)v.findViewById(R.id.Nume)).setText(num);
String tdoc = String.format(tipdoc.get(pos));
((TextView)v.findViewById(R.id.TDoc)).setText(tdoc);
if (formatdoc.get(pos).equals("doc")){
((ImageView)v.findViewById(R.id.list_image)).setImageResource(R.drawable.doc);
}
else if (formatdoc.get(pos).equals(".xlsx") || formatdoc.get(pos).equals("xls")) ((ImageView)v.findViewById(R.id.list_image)).setImageResource(R.drawable.xls);
else ((ImageView)v.findViewById(R.id.list_image)).setImageResource(R.drawable.pdf);
return v;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
you have to change the value of nume var,because in your code its the same
try this code...
et.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s,
int start, int count, int after)
{
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s,int start, int before, int count)
{
textlength = et.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array_location.length; i++)
{
if (textlength <= listview_array_location[i].length())
{
if(et.getText().toString().equalsIgnoreCase((String)listview_array_location[i].subSequence(0,textlength)))
{
array_sort.add(listview_array[i]);
}
}
}
AppendList(array_sort);
}
});
}
public void AppendList(ArrayList<String> str)
{
listview_arr = new String[str.size()];
listview_arr = str.toArray(listview_arr);
setListAdapter(new bsAdapter(this));
}
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
// TODO Auto-generated constructor stub
this.cntx=context;
}
public int getCount()
{
// TODO Auto-generated method stub
return listview_arr.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return listview_arr[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return listview_array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.search_list_item, null);
TextView tv=(TextView)row.findViewById(R.id.title);
tv.setText(listview_arr[position]);
return row;
}
}