I have a custom listview that contains an edittext,checkbox and two text views.Now i am hving a problem with the edittext values in my code.I am not able to get the correct value from the edittext.And also if i set the value of an edit text at one position in the list,that value is also set to edittexts at random positions in the listview.And i have the common problem of the values changing on scroll.Following is the code:
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assess_list);
prev = getIntent();
final ListView listview = (ListView) findViewById(R.id.studentsListView);
listview.setAdapter(new AssessmentAdapter(this, R.layout.assessment,
StudentNames.student_name, StudentNames.studentRollNo));
}
Adapter:
public class AssessmentAdapter extends ArrayAdapter<String> {
Context context;
ViewHolder holder;
CheckBox present;
EditText marks;
int pos;
public static ArrayList<String> studentNames,studentRollNo,studentsPresent,marksObtainedList;
public AssessmentAdapter(Context context, int textViewResourceId,ArrayList<String> studentNames,ArrayList<String> studentRollNo) {
super(context, textViewResourceId,studentNames);
// TODO Auto-generated constructor stub
this.context=context;
AssessmentAdapter.studentNames=studentNames;
AssessmentAdapter.studentRollNo=studentRollNo;
studentsPresent=new ArrayList<String>();
marksObtainedList=new ArrayList<String>();
Log.d("No. of students",""+studentRollNo.size());
for(int i=0;i<studentNames.size();i++)
{
studentsPresent.add("1");
marksObtainedList.add("0");
}
}
static class ViewHolder {
CheckBox presentCB;
TextView name,Rno;
EditText marksObtained;
Button save;
}
public View getView(final int pos,View convertview,ViewGroup parent)
{
try
{
holder=null;
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertview==null)
{
//rowView=inflater.inflate(org.example.attendance.R.layout.list_radio,parent,false);
convertview=inflater.inflate(R.layout.assessment,null);
holder=new ViewHolder();
holder.presentCB=(CheckBox)convertview.findViewById(org.example.attendance2.R.id.presentCB);
holder.name=(TextView)convertview.findViewById(org.example.attendance2.R.id.studNameTV);
holder.Rno=(TextView)convertview.findViewById(org.example.attendance2.R.id.studRollNoTV);
holder.marksObtained=(EditText)convertview.findViewById(org.example.attendance2.R.id.marksET);
holder.save=(Button)convertview.findViewById(org.example.attendance2.R.id.saveButton);
convertview.setTag(holder);
}
else
{
holder=(ViewHolder) convertview.getTag();
}
holder.name.setText(studentNames.get(pos));
holder.Rno.setText(studentRollNo.get(pos));
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
holder.marksObtained.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
marksObtainedList.set(pos, arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
holder.presentCB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(studentsPresent.get(pos).equals("1"))
{
studentsPresent.set(pos, "0");
}
else
{
studentsPresent.set(pos, "1");
}
}
});
//if(RadioChecked[pos])
if(studentsPresent.get(pos).equals("1"))
{
holder.presentCB.setChecked(true);
}
// else if(!RadioChecked[pos])
else if(studentsPresent.get(pos).equals("0"))
{
holder.presentCB.setChecked(false);
}
if(holder.marksObtained.getText().toString().equals(""))
{
marksObtainedList.set(pos,"0");
}
else
{
String marks=holder.marksObtained.getText().toString();
marksObtainedList.set(pos,marks);
Log.d(""+pos,marksObtainedList.get(pos));
}
holder.marksObtained.setText(marksObtainedList.get(pos));
}catch(Exception e)
{
}
return convertview;
}
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int arg0)
{
return true;
}
}
the problem is all about relate to focus . see here , it may help you.
Focusable EditText inside ListView
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.
I am using ListView to show TextViews in some rows and not others. I don't know how many items there will be, it runs fine but when I scroll down the display changed.
I'm working on an app where users fill reports and polls. In an activity I have a ListView where children contain EditTexts, Checkbox and TextView.
The problem with EditTexts and Checkbox was that when scrolling, the content that they have is lost. I was able to fix the Checkbox problem by saving the check status in an array, but I can't fix the problem with EditTexts. I know that there are some questions about this particular issue but the solutions that they provided doesn't seem to work.
Im using this BaseAdapter.
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<Model> models = new ArrayList<>();
private ModelTable avModelTable = new ModelTable();
private BrandTable brandTable = new BrandTable();
public ProductAdapter(Context mContext, List<Model> models) {
this.mContext = mContext;
this.models = models;
}
#Override
public int getCount() {
return models.size();
}
#Override
public Model getItem(int i) {
return models.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ProductHolder item = new ProductHolder();
View row = view;
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.product_item, viewGroup, false);
item.nameProduct = (TextView) row.findViewById(R.id.nameProduct);
item.subCategoryProduct = (TextView) row.findViewById(R.id.subCategoryProduct);
item.productGroup = (RadioGroup) row.findViewById(R.id.groupRadioProduct);
item.oos_product = (RadioButton) row.findViewById(R.id.oos_product);
item.av_product = (RadioButton) row.findViewById(R.id.av_product);
item.shelfProduct = (EditText) row.findViewById(R.id.shelfProduct);
item.quantityProduct = (EditText) row.findViewById(R.id.quantityProduct);
item.priceProduct = (EditText) row.findViewById(R.id.priceProduct);
item.layoutBrand = (LinearLayout) row.findViewById(R.id.layoutBrand);
item.avBrand = (EditText) row.findViewById(R.id.avBrand);
row.setTag(item);
} else {
item = (ProductHolder) row.getTag();
}
final Model model = models.get(i);
item.nameProduct.setText(model.getProduct_name());
item.subCategoryProduct.setText(brandTable.getBrandName(model.getBrand_id()));
if (model.getQuantity() != 0) {
item.quantityProduct.setText(String.valueOf(model.getQuantity()));
}
if (model.getShelf() != 0) {
item.shelfProduct.setText(String.valueOf(model.getShelf()));
}
if (model.getPrice() != null) {
item.priceProduct.setText(model.getPrice());
}
if (model.getBrand_id() == 1) {
item.layoutBrand.setVisibility(View.GONE);
item.avBrand.setVisibility(View.GONE);
item.productGroup.setVisibility(View.VISIBLE);
item.oos_product.setVisibility(View.VISIBLE);
item.av_product.setVisibility(View.VISIBLE);
switch (model.getAv()) {
case 0:
item.oos_product.setChecked(true);
break;
case 1:
item.av_product.setChecked(true);
break;
default:
break;
}
item.productGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i) {
case R.id.oos_product:
avModelTable.updateAv(model.getId(), 0);
break;
case R.id.av_product:
avModelTable.updateAv(model.getId(), 1);
break;
default:
break;
}
}
});
} else {
item.layoutBrand.setVisibility(View.VISIBLE);
item.avBrand.setVisibility(View.VISIBLE);
item.productGroup.setVisibility(View.GONE);
item.oos_product.setVisibility(View.GONE);
item.av_product.setVisibility(View.GONE);
item.avBrand.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
if (arg0.toString().equals("")) {
avModelTable.updateAv(model.getId(), 0);
} else avModelTable.updateAv(model.getId(), Integer.parseInt(arg0.toString()));
}
});
}
item.shelfProduct.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
if (arg0.toString().equals("")) {
avModelTable.updateShelf(model.getId(), 0);
} else avModelTable.updateShelf(model.getId(), Integer.parseInt(arg0.toString()));
}
});
item.quantityProduct.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
if (arg0.toString().equals("")) {
avModelTable.updateQuantity(model.getId(), 0);
} else
avModelTable.updateQuantity(model.getId(), Integer.parseInt(arg0.toString()));
}
});
item.priceProduct.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
if (arg0.toString().equals("")) {
avModelTable.updatePrice(model.getId(), null);
} else
avModelTable.updatePrice(model.getId(), arg0.toString());
}
});
return row;
}
private class ProductHolder {
private TextView nameProduct, subCategoryProduct;
private RadioButton oos_product, av_product;
private RadioGroup productGroup;
private EditText shelfProduct, quantityProduct, priceProduct, avBrand;
private LinearLayout layoutBrand;
}
}
I made a test code using your adapter but with different views/models and tried it but it didn't work. It only worked after I replaced View row = view; with View row = null; at the start of your getView method, forcing the code to inflate the views every time. That's why I believe the problem is at the item = (ProductHolder) row.getTag(); part. Perhaps the ProductHolder model is not correct.
I have two EditTexts in my ListView. All I want is adding a TextWatcher to both the EditTexts , so I can avoid duplicating and changing values in it while scrolling. I can successfully add the TextWatcher to one of the EditTexts, but could not implement for two EditTexts. I tried other answers from stackoverflow. But I didn't get desired output.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orders);
list = (ListView)findViewById(R.id.list1);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
SelectItems();
ViewItems();
}
public List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp"
+ " from itemmaster", null);
c.moveToFirst();
while (c.moveToNext()){
datanums.put("name",c.getString(c.getColumnIndex("im_desc")));
datanums.put("code", c.getString(c.getColumnIndex("im_code")));
datanums.put("imsrp",c.getString(c.getColumnIndex("im_srp")));
datas.add(datanums);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
public void ViewItems() {
// TODO Auto-generated method stub
arrTemp = new String[datas.size()];
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
}
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.srp);
holder.textview3 = (TextView) convertView.findViewById(R.id.code);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
holder.editText2 = (EditText) convertView.findViewById(R.id.pcs);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
String [] names = new String[550];
String [] codes = new String[550];
String [] prize = new String[550];
DatabaseHelper dbHelper = new DatabaseHelper(Orders.this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp "
+ " from itemmaster", null);
Log.v("item detailss", c.toString());
c.moveToFirst();
while (c.moveToNext()){
String cod = c.getString(c.getColumnIndex("im_code"));
codes[c.getPosition()] =cod;
String desc1 = c.getString(c.getColumnIndex("im_desc"));
names[c.getPosition()] = desc1;
String price = c.getString(c.getColumnIndex("im_srp"));
prize[c.getPosition()] = price;
}
newDB.close();
holder.textView1.setText(names[position+1]);
holder.textview3.setText(codes[position+1]);
holder.textView2.setText(prize[position+1]);
holder.editText1.setText(arrTemp[holder.ref]);
holder.editText2.setText(arrTemp[holder.ref]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
datas.get(position).put("pref", holder.editText1.toString().trim());
}
});
return convertView;
}
private class ViewHolder {
TextView textView1,textView2,textview3;
EditText editText1,editText2;
public int ref;
}
}
please help me to do this in right way.
Recently I had a similar problem, here is how I solved it using HashMap:
In the adapter constructor, initialize HashMap and make sure to clear it:
public MyAdapter(Context context, String[] texts){
this.context = context;
this.texts = texts;
hashMapTexts = new HashMap<String,String>();
for(String text: texts){
hashMapTexts.put(text, "");
}
Then, correct your private class ViewHolder inside the adapter like that:
private class ViewHolder {
private TextView listItemTextView;
private EditText listItemEditText;
private int position;
public ViewHolder(View view) {
listItemTextView = (TextView)view.findViewById(R.id.list_item_text_view);
listItemEditText = (EditText)view.findViewById(R.id.list_item_edit_text);
}
}
Then, initialize the ViewHolder in the overriden getView() method:
if(convertView == null){
convertView = View.inflate(context, R.layout.list_item, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
Get the position of the ViewHolder in the same method:
viewHolder.position = position;
Set the texts for your views:
viewHolder.listItemTextView.setText(texts[position]);
viewHolder.listItemEditText.setText(hashMapTexts.get(texts[position]));
and now use the TextWatcher:
viewHolder.listItemFormEditText.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) {
hashMapTexts.put(texts[viewHolder.position], s.toString());
}
});
return convertView;
I suggest you to start with easier case, like mine, then apply it to your specific scenario.
Use different textwatchers for each edit text if you want to perform
different operations on each edit text
EditText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Apply same for other EditText too
et1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
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;
}
}
I want to have a listview with textview + check box. I was able to create the listview. I can capture listview item select. However when I try to capture check box select, unselect I get a null pointer exception. How to write the setOnCheckedChangeListener() for the check box..
public class LocationActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
final List<String> locLables = new ArrayList<String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.add(cursor.getString(1));
} while (cursor.moveToNext());
}
}
//String[] locLables = new String[] {"Home","University","Office"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locationmain_entry,R.id.textView12, locLables);
//cb gives a null pointer exception
CheckBox cb = (CheckBox) listview.findViewById(R.id.checkBox12);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("selected");
}else if(!isChecked){
System.out.println("not selected");
}
}
});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
You can maintain seperate adpater class so that you can achive this easily....
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);
CheckBox cb=(CheckBox)row.findViewById(R.id.cb01);
tv.setText(listview_arr[position]);
cb.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(cb.ischecked)
{
//ur code
}
else //ur code
}
});
return row;
}
}
Do not use listview.findViewById(), just use findViewById() like you did for your list.
Unless the checkbox is part of each of the list items, in which case you would have to access the checkbox from within the getView() of your ListAdapter.