I am having problem in getting text from EditText in the listview adapter. For example, when I click "9", it doesn't give me 9. Instead, I always get 3. I am unable to figure the reason behind this. Please inform me where I am going wrong.
This is my code for your perusal. Thank you in advance!
class Planet {
String name;
int distance;
String quantità;
boolean selected = false;
public Planet(String name, int distance, String quantità) {
super();
this.name = name;
this.distance = distance;
this.quantità = quantità;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getQuantità() {
return quantità;
}
public void setQuantità(String quantità) {
this.quantità = quantità;
}
}
public class PlanetAdapter extends ArrayAdapter<Planet>{
private List<Planet> planetList;
private Context context;
ArrayList<Planet> objects;
public PlanetAdapter(List<Planet> planetList, Context context) {
super(context, R.layout.single_listview_item, planetList);
this.planetList = planetList;
this.context = context;
}
public static class PlanetHolder {
public TextView planetName;
public TextView distView;
public CheckBox chkBox;
public EditText edit;
public String quantità="3";
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final PlanetHolder holder = new PlanetHolder();
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_listview_item, null);
holder.planetName = (TextView) v.findViewById(R.id.name);
holder.distView = (TextView) v.findViewById(R.id.dist);
holder.chkBox = (CheckBox) v.findViewById(R.id.chk_box);
holder.edit = (EditText) v.findViewById(R.id.editText);
holder.edit.setVisibility(View.GONE);
holder.edit.setEnabled(false);
holder.chkBox.setOnCheckedChangeListener((MainActivity) context);
//
holder.chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.chkBox.isChecked()) {
holder.edit.setVisibility(View.VISIBLE);
holder.edit.setEnabled(true);
holder.edit.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) {
holder.quantità = holder.edit.getText().toString();
System.out.println("leggo questo dalla edittext:"+ holder.edit.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
} else {
holder.edit.setVisibility(View.GONE);
holder.edit.setEnabled(false);
holder.edit.setText(null);
}
}
});
} else {
}
Planet p = planetList.get(position);
p.setQuantità(holder.quantità);
holder.planetName.setText(p.getName());
holder.distView.setText("" + p.getDistance());
holder.chkBox.setChecked(p.isSelected());
holder.chkBox.setTag(p);
holder.edit.setEnabled(false);
return v;
}
ArrayList<Planet> getBox() {
ArrayList<Planet> box = new ArrayList<Planet>();
for (Planet p : planetList) {
if (p.selected)
box.add(p);
}
return box;
}
}
Replace your getView() method with this:
View row = convertView;
PlanetHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.single_listview_item, parent, false);
holder = new PlanetHolder();
holder.planetName = (TextView) row.findViewById(R.id.name);
holder.distView = (TextView) row.findViewById(R.id.dist);
holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
holder.edit = (EditText) row.findViewById(R.id.editText);
row.setTag(holder);
} else {
holder = (PlanetHolder) row.getTag();
}
final Planet p = planetList.get(position);
holder.chkBox.setOnCheckedChangeListener((MainActivity) context);
holder.chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.chkBox.isChecked()) {
holder.edit.setVisibility(View.VISIBLE);
holder.edit.setEnabled(true);
holder.edit.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) {
p.setQuantità(holder.edit.getText().toString().trim());
}
});
} else {
holder.edit.setVisibility(View.GONE);
holder.edit.setEnabled(false);
holder.edit.setText(null);
}
}
});
holder.planetName.setText(p.getName());
holder.distView.setText("" + p.getDistance());
holder.chkBox.setChecked(p.isSelected());
holder.chkBox.setTag(p);
holder.edit.setEnabled(false);
return row;
You can get text of your listview by this way, Use this in your activity or fragment. Here items is an arraylist.
for (int i = 0; i < items.size(); i++) {
View wantedView = recyclerView.getChildAt(i);
EditText editqty = (EditText) wantedView.findViewById(R.id.edtTxtQty);
if ((editqty.getText().toString().length() > 0)) {
//store edit text value in any arraylist or array by editqty.getText().toString()
}
}
You have fix value of PlanetHolder class so you always get value '3'
public static class PlanetHolder {
public TextView planetName;
public TextView distView;
public CheckBox chkBox;
public EditText edit;
public String quantità="3";
}
remove public String quantitàfix value.
and Second is you have declare View v = convertView; but in if condition you can check this if(convertView == null) { so replace convertView to v
Related
I'm working on a ListView which use an Adapter and ViewHolder component in aim to ensure stability of items but I'm facing an unexpected behavior.
At first I need to explain that my items aren't static : each item is a row with a checkbox and when the box is checked a form appears below to ask user to give more informations.
But at the moment when user check the box and enter some text in the form, another item react the same way :
checkbox checked
the same text in the form
The unwanted reacting item is not drawn at the same time ( both items aren't visible together, a scroll is needed to see one or the other)
It's not accurate but my activity setting windowSoftInputMode is adjustNothing
Thanks for any answer!
Great day
Here is my code
private List<Object> mObjects;
private LongSparseArray<Account> uAccounts;
ImageView illustration;
TypefaceTextView explanation;
ProgressBar load;
ListView lv;
private Context context;
private AccountExpListAdapter accountExpListAdapter;
public int occurences;
private boolean allGood = true;
private void initUI() {
if (getActivity() != null && getActivity().getApplicationContext() != null) {
accountExpListAdapter = new AccountExpListAdapter(getActivity().getApplicationContext(),
mObjects);
if (lv != null) {
lv.setAdapter(accountExpListAdapter);
}
}
if (load != null)
load.setVisibility(View.GONE);
}
static class ViewHolder {
ImageView logo;
TextView tv;
RelativeLayout header;
RelativeLayout form;
CheckBox checkBox;
EditText email_ET;
EditText pwd_ET;
}
public class AccountExpListAdapter extends ArrayAdapter<Object> {
private List<Object> objects;
private Context context;
public AccountExpListAdapter(Context context, List<Object> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
this.context = context;
this.objects = objects;
}
#Override
public int getCount() {
return objects.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (vi == null) {
LayoutInflater inflater = LayoutInflater.from(context);
vi = inflater.inflate(R.layout.selectable, parent, false);
holder = new ViewHolder();
holder.logo = (ImageView) vi.findViewById(R.id.logo);
holder.tv = (TextView) vi.findViewById(R.id.name);
holder.header = (RelativeLayout) vi.findViewById(R.id.header);
holder.form = (RelativeLayout) vi.findViewById(R.id.form);
holder.checkBox = (CheckBox) vi.findViewById(R.id.box);
holder.email_ET = (EditText) vi.findViewById(R.id.email_edit_text);
holder.pwd_ET = (EditText) vi.findViewById(R.id.pwd_edit_text);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
final Object object = objects.get(position);
Glide.with(context).load(Uri.parse(object.getLogo())).into(holder.logo);
holder.tv.setText(object.getName());
final ViewHolder finalHolder = holder;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isChecked = ((CheckBox) view).isChecked();
manageKeyboard(isChecked);
int visibility = isChecked ? View.VISIBLE : View.GONE;
finalHolder.form.setVisibility(visibility);
if (!isChecked) {
uAccounts.remove(object.getId());
} else {
uAccounts.put(object.getId(), new Account());
allGood = false;
lv.smoothScrollToPositionFromTop(position + 1, 150, 500);
finalHolder.email_ET.requestFocus();
}
}
});
holder.header.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finalHolder.checkBox.performClick();
}
});
if (holder.form != null) {
holder.email_ET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (!checkEmailFormat(editable.toString())) {
finalHolder.email_ET.setError(getString(R.string.email_invalid));
allGood = false;
return;
} else {
allGood = true;
}
Long objectId = object.getId();
Account a;
if (uAccounts.indexOfKey(objectId) < 0) {
a = new Account();
} else {
a = uAccounts.get(objectId);
}
a.setUsername(editable.toString());
uAccounts.put(objectId, a);
}
});
holder.pwd_ET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length() == 0) {
finalHolder.pwd_ET.setError(getString(R.string.password_invalid));
allGood = false;
return;
} else {
allGood = true;
}
Long objectId = object.getId();
Account a;
if (uAccounts.indexOfKey(objectId) < 0) {
a = new Account();
} else {
a = uAccounts.get(objectId);
}
a.setEncrypted_password(editable.toString());
uAccounts.put(objectId, a);
}
});
}
return vi;
}
}
}
the code is quite complex for the checkbox due to the show/hide form but does it may produce this unwanted listview items behavior?
Thanks
I have custom list view with checkbox, when I executed in my small mobile phone, if list view already had 5 items, then when I checked item 1, then item 5 will be checked also, if I checked item 5 then item 1 will be checked also, it happened with item (2-6,3-7,4-8, etc).
But if I had 4 items in my listview, it wont be happened. Here my listview adapter :
http://pastebin.com/mTEiXryf
Could you help me to solve my bug ? Thanks in advance
I suggest you to use Recyclerview
public class CardViewDataAdapter extends
RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private List<Student> stList;
public CardViewDataAdapter(List<Student> students) {
this.stList = students;
}
// Create new views
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardview_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final int pos = position;
viewHolder.tvName.setText(stList.get(position).getName());
viewHolder.tvEmailId.setText(stList.get(position).getEmailId());
viewHolder.chkSelected.setChecked(stList.get(position).isSelected());
viewHolder.chkSelected.setTag(stList.get(position));
viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Student contact = (Student) cb.getTag();
contact.setSelected(cb.isChecked());
stList.get(pos).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public CheckBox chkSelected;
public Student singlestudent;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemLayoutView.findViewById(R.id.tvEmailId);
chkSelected = (CheckBox) itemLayoutView
.findViewById(R.id.chkSelected);
}
}
// method to access in activity after updating selection
public List<Student> getStudentist() {
return stList;
}
}
OR
If you want to use listview,then better you maintain Boolean array for checkbox,try this way this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
Here is solution- You had added holder.chkbox.setOnClickListener at wrong place just put it at right place. Replace your code with this code
if(convertView == null) {
convertView = myInflater.inflate(R.layout.customviewitemcashier, null);
holder = new ViewHolder();
holder.tvitemcode = (TextView) convertView.findViewById(R.id.tvitemcode);
holder.tvitemname = (TextView) convertView.findViewById(R.id.tvitemname);
holder.tvprice = (TextView) convertView.findViewById(R.id.tvprice);
holder.tvsubtotal = (TextView) convertView.findViewById(R.id.tvsubtotal);
holder.edtqty = (EditText) convertView.findViewById(R.id.edtqty);
holder.imgincrease = (TextView) convertView.findViewById(R.id.imgincrease);
holder.imgdecrease = (TextView) convertView.findViewById(R.id.imgdecrease);
holder.imgitem= (ImageView) convertView.findViewById(R.id.imgitem);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.chkbox.isChecked()) {
SQLiteDatabase dbinsert = dbHelper.getWritableDatabase();
String SQLinsert = "INSERT INTO itemcheckedcontainer (`item_code`) VALUES (" +
"'" + DataProcessorResult.get(position).getItemCode() + "')";
dbinsert.execSQL(SQLinsert);
} else {
SQLiteDatabase dbdelete = dbHelper.getWritableDatabase();
String SQLdelete = "DELETE FROM itemcheckedcontainer WHERE item_code=" +
"'" + DataProcessorResult.get(position).getItemCode() + "'";
dbdelete.execSQL(SQLdelete);
}
}
});
Your problem solved.
I am android developer, I have a custom listview with a checkbox. This layput also contain a delete button. I want when I click on cheakbox all the item in a particular row is selected and on click of delete it is deleted.
The problem is when I click on delete button I get a list of +1 row value.
Initially I already define :
int position=0;
btmsgdelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("request send for message delete");
for(Message msg:almsg) {
if(msg.isSelected()) {
CheckBox chk = (CheckBox)findViewById(R.id.checkBox1);
System.out.println("msg is selected");
msgid=almsg.get(position).getEmpid();
System.out.println(msgid);
empname=almsg.get(position).getEmpname();
System.out.println(empname);
msgheader=almsg.get(position).getHeader();
System.out.println(msgheader);
}
}
Try this sample code
public class MainActivity extends Activity {
private int textViewResourceId;
private ArrayList<CompareListData> searchResults;
private ListView lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchResults = GetSearchResults();
lst = (ListView) findViewById(R.id.list);
findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < searchResults.size(); i++) {
if (searchResults.get(i).getSelected()) {
searchResults.remove(i);
}
}
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
});
System.out.println("size " + searchResults.size());
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
private ArrayList<CompareListData> GetSearchResults() {
ArrayList<CompareListData> results = new ArrayList<CompareListData>();
CompareListData sr1 = new CompareListData();
sr1.setName("John Smith");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Jane Doe");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Steve Young");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Fred Jones");
results.add(sr1);
return results;
}
}
CompareListData.java
public class CompareListData {
String name;
boolean selected;
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Adapter.java
public class Adapter extends BaseAdapter{
public static int count = 0;
public LayoutInflater inflater;
public static ArrayList<CompareListData> selectedId;
public ArrayList<CompareListData> listObjects;
Context contex;
public Adapter(Context context, int textViewResourceId,
ArrayList<CompareListData> objects) {
super();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listObjects = objects;
this.contex = context;
}
public static class ViewHolder
{
TextView txtViewLoanName;
CheckBox chkSelected;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView==null)
{
final ViewHolder holder = new ViewHolder();
view = inflater.inflate(R.layout.row_comparelist, null);
holder.txtViewLoanName= (TextView) view.findViewById(R.id.rowcomparelist_tv_loanname);
holder.chkSelected= (CheckBox) view.findViewById(R.id.rowcomparelist_chk_selected);
holder.chkSelected.setId(position);
holder.chkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CompareListData element = (CompareListData) holder.chkSelected.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(holder);
holder.chkSelected.setTag(listObjects.get(position));
}
else{
view = convertView;
((ViewHolder) view.getTag()).chkSelected.setTag(listObjects.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtViewLoanName.setText(listObjects.get(position).getName());
holder.chkSelected.setChecked(listObjects.get(position).getSelected());
return view;
}
public int getCount() {
return listObjects.size();
}
public Object getItem(int position) {
return listObjects.get(position);
}
public long getItemId(int position) {return position;
}
}
I have a Custom adapter class, as follows.When I select one checkbox,other checkboxes also gets selected after 7-8 rows. Even if setonclicklisterner is not implement, checkboxes behaves the same. I need a proper solution. I searched a lot but not getting the solution.
How can I stop avoiding the multiple selection of checkboxes?
public class CustomAdapter extends ArrayAdapter<Custom>{
private ArrayList<Custom> entries;
private Activity activity;
private Context context;
private qrusers qrusers;
private String[] udis;
ArrayList<String> userid= new ArrayList<String>();
boolean[] checkBoxState;
LayoutInflater vi;
public CustomAdapter(Context context, ArrayList<Custom> entries,String []udis) {
super(context,0,entries);
this.entries = entries;
this.context= context;
this.udis=udis;
checkBoxState=new boolean[entries.size()];
this.qrusers =(qrusers) context;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
public CheckBox chek;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = vi.inflate(R.layout.checkboxlist, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.contactname);
holder.item2 = (TextView) v.findViewById(R.id.companyname);
holder.chek=(CheckBox)v.findViewById(R.id.checboxlist);
holder.chek.setTag(udis[position]);
v.setTag(holder);
/* holder.chek.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private String s;
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
checkBoxState[position]=true;
// isChecked=true;
s=(String)buttonView.getTag();
Log.e("IDDDDDDDD", s);
userid.add(s);
Log.e("ADDED ID", userid.toString());
}
else{
checkBoxState[position]=false;
s=(String)buttonView.getTag();
userid.remove(s);
Log.e("Removed ID", userid.toString());
}
}
});*/
holder.chek.setOnClickListener(new OnClickListener() {
private String s;
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()){
checkBoxState[position]=true;
// isChecked=true;
s=(String)v.getTag();
Log.e("IDDDDDDDD", s);
userid.add(s);
Log.e("ADDED ID", userid.toString());
}
else{
checkBoxState[position]=false;
s=(String)v.getTag();
userid.remove(s);
Log.e("Removed ID", userid.toString());
}
}
});
holder.chek.setChecked(checkBoxState[position]);
CheckBox result = (CheckBox)convertView;
if (result == null) {
result = new CheckBox(context);
}}
else
holder=(ViewHolder)v.getTag();
final Custom custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getcustomBig());
holder.item2.setText(custom.getcustomSmall());
}
return v;
}
public ArrayList<String> getUserid() {
return userid;
}
public void setUserid(ArrayList<String> userid) {
this.userid = userid;
}
}
use this code for base adapter.
public class CollageView extends BaseAdapter {
Context context;
ArrayList<String> image_arrylist = new ArrayList<String>();
File file;
Bitmap bm;
LayoutInflater inflater;
ImageView imageview;
ViewHolder holder = null;
int position;
public CollageView(Context c, ArrayList<String> array_list) {
context = c;
imageview = new ImageView(c);
image_arrylist = array_list;
inflater = LayoutInflater.from(context);
System.out.println("Size-&&7" + image_arrylist.size());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return image_arrylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View v = convertView;
if (v == null) {
v = inflater.inflate(R.layout.collage_image_row, null);
holder = new ViewHolder();
holder.image = (ImageView) v
.findViewById(R.id.imageView_collage);
holder.checkbox = (CheckBox) v
.findViewById(R.id.itemCheckBox_collage_image);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.checkbox.setId(position);
holder.image.setId(position);
if (CollageViewActivity.checkbox_boolean == true) {
holder.checkbox.setVisibility(View.VISIBLE);
}
System.out.println("aname" + aname);
holder.checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("click-1");
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
int id = cb.getId();
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.checkbox.setChecked(thumbnailsselection[position]);
holder.id = position;
System.out.println("set image..." + image_arrylist.get(position));
file = new File(image_arrylist.get(position));
String ext = file.toString();
if (checkVideo(file)) {
System.out.println("video exist " + file.exists());
holder.image.setScaleType(ImageView.ScaleType.CENTER);
aq.id(holder.image).image(
getVideoThumnail(image_arrylist.get(position)));
} else {
System.out.println("file exist " + file.exists());
holder.image.setScaleType(ImageView.ScaleType.CENTER);
aq.id(holder.image).image(file, 300);
}
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("labelorcollage"
+ GeneralClass.lableorcollage
+ image_arrylist.size());
GeneralClass.checkfullimage = true;
// gridview.setVisibility(View.GONE);
playout_image.setVisibility(View.VISIBLE);
playout_grid.setVisibility(View.GONE);
}
});
return v;
}
public class ViewHolder {
TextView imageTitle;
ImageView image;
RelativeLayout layout;
CheckBox checkbox;
int id;
}
}
//try to replace this peace of code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = vi.inflate(R.layout.checkboxlist, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.contactname);
holder.item2 = (TextView) v.findViewById(R.id.companyname);
holder.chek=(CheckBox)v.findViewById(R.id.checboxlist);
v.setTag(holder);
}else{
holder=(ViewHolder)v.getTag();
}
holder.chek.setChecked(checkBoxState[position]);
holder.chek.setTag(position);
holder.chek.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
checkBoxState[(Integer)((CheckBox)compoundButton).getTag()]=b;
if(b){
userid.add(udis[(Integer)((CheckBox)compoundButton).getTag()]);
}else{
userid.remove(udis[(Integer)((CheckBox)compoundButton).getTag()]);
}
}
});
final Custom custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getcustomBig());
holder.item2.setText(custom.getcustomSmall());
}
return v;
}
check out this link: http://sunil-android.blogspot.in/2013/04/android-listview-checkbox-example.html and follow steps he took it might help you! it helped me too to have checked only the checkbox i selected.
i have created a listview with checkbox,edittext and textview.
data is populated in listview with sql server. but i am not being able to use onCheckedChangedListener on checkbox. so that on clicking the checkbox corresponding data of textview and edittext is not being saved..
i know i am doing mistake somewhere in my adapter class..
How to save data and what logic should i use in onCheckedChangedListener in my adapter class?
code for pojo class
public class Model {
public String name="";
public boolean selected=false;
public String score="";
public Model(String name) {
this.name = name;
selected = false;
score="";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
code for Adapter class
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public MyAdapter(Activity context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.scores.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void afterTextChanged(Editable s)
{
}
});
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
((ViewHolder) view.getTag()).scores.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
code for MainActivity class
public class MainActivity extends Activity {
ListView listView;
Button btnSave;
Connection connect;
ArrayAdapter<Model> adapter;
MyConnection mycon;
List<Model> list = new ArrayList<Model>();
List<String>data=new ArrayList<String>();
List<String>data2=new ArrayList<String>();
StringBuilder sb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mycon=new MyConnection(getApplicationContext());
listView = (ListView) findViewById(R.id.my_list);
btnSave = (Button)findViewById(R.id.btnSave);
sb=new StringBuilder();
adapter = new MyAdapter(this,getModel());
listView.setAdapter(adapter);
if(list.isEmpty()){
Toast.makeText(getApplicationContext(), "kuldeep", Toast.LENGTH_LONG).show();
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected()+"address: "+list.get(i).getScore().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
private List<Model> getModel() {
list.clear();
try{
Statement smt=mycon.connection().createStatement();
ResultSet rs=smt.executeQuery("WORKINGTYPE");
while(rs.next()){
list.add(new Model(rs.getString("FIELD_NAME")));
}
}catch(Exception e){
e.printStackTrace();
}
/* list.add(new Model("kuldeep"));
list.add(new Model("sandeep"));
list.add(new Model("ravi"));
list.add(new Model("pradeep"));
list.add(new Model("praveena"));
list.add(new Model("ruchi"));
list.add(new Model("vikas"));
list.add(new Model("sonu"));
list.add(new Model("ashu"));
*/
return list;
}
}
for saving data of textview and EditText what logic should i use and where in Adapter clss i should write it..
May not be a solution, but a suggestion.
Prefer not to declare your Listeners inside an 'if' condition. What I meant is,
IF convertview == null
find views
ELSE
getTag()
Rest of the codes
Is it that your checkbox event is not firing?
I use setOnClickListener for my Checkbox events:
CheckBox checkbox = (CheckBox)view.findViewById(R.id.item_checkbox);
checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Mark model as selected/not selected
if (model.isSelected())
model.markAsNotSelected();
else
model.markAsSelected();
}
});
I know it's an old question, but if anyone else is facing same problem, replace the Adapter class with the following code.
public class MyAdapter extends ArrayAdapter<Model> implements TextWatcher{
private final List<Model> list;
private final Context context;
public MyAdapter(Context context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder = null;
if (convertView == null){
LayoutInflater inflator = LayoutInflater.from(context);
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
convertView.setTag(viewHolder);
}
else
{
convertView = (ViewHolder) convertView.getTag();
}
viewHolder.scores.addTextChangedListener(this)
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
}