How to get selected checkbox value - android

I have implemented a Names with a check box in a List, Here my aim is to check the check box and get the respective name. Here i have written code in adapter and in activity class but i am not getting any value and it is not showing any errors.
Here my adapter code..
public Add_member_adapter(Context a, ArrayList<ItemsModel> d) {
context = a;
data = d;
checkedHolder = new boolean[data.size()];
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public final Object getItem(int position) {
return data.get(position);
}
public final long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView Name, UserId_Fk;
CheckBox chkbox;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("getview:", "position=" + position);
vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.add_members_list_item, null);
holder = new ViewHolder();
holder.Name = (TextView) vi.findViewById(R.id.Name);
holder.UserId_Fk = (TextView) vi.findViewById(R.id.CusId_Fk);
holder.chkbox = (CheckBox) vi.findViewById(R.id.chkbox);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (data.size() <= 0) {
vi.setVisibility(View.GONE);
} else {
tempValues = null;
tempValues = (ItemsModel) data.get(position);
holder.Name.setText(tempValues.getItemName().toString());
Log.i(TAG, "Name " + tempValues.getItemName().toString());
holder.UserId_Fk.setText(tempValues.getUserId_Fk().toString());
holder.chkbox.setChecked(false);
holder.chkbox.setChecked(checkedHolder[position]);
Log.i(TAG, "Position " + checkedHolder[position]);
holder.chkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
checkedHolder[position] = isChecked;
Log.i(TAG, "Position " + checkedHolder[position]);
}
});
}
return vi;
}
In Activity...
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// String Name = list.getItemAtPosition(position).toString();
// CheckBox cb = (CheckBox) view.findViewById(R.id.chkbox);
// TextView tv = (TextView) view.findViewById(R.id.Name);
for (int i = 0; i < adapter.getCount(); i++) {
if (adapter.checkedHolder[i]) {
// get all name values that checked by user
Name = ((TextView) findViewById(R.id.Name)).getText()
.toString();
Log.i(TAG, "Name " + Name);
}
}
}
});

change your setOnItemClikListener as below
for (int i = 0; i < adapter.getCount(); i++) {
if (adapter.checkedHolder[i]) {
// get all name values that checked by user
Name = data.get(i).getItemName().toString();
Log.i(TAG, "Name " + Name);
}
in getView relpace holder.chkbox.setChecked(false); with below line ;
holder.chkbox.setOnCheckedChangeListener(null);

Related

check box unchecked issue when i scroll the custom listview android

listview row having multiple checkboxex, when i checked the checkboxex then if i scroll the listview, its automatically unchecked the checkboxes. how can fix this issue. here is my getView method
public View getView(final int position, View convertView, ViewGroup parent) {
final QuestionRadioHolder questionRadioHolder;
final QuestionCheckboxHolder questionCheckboxHolder;
final Model rowItem = getItem(position);
final int type = getItemViewType(position);
if (type == TYPE1) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.radio_layout, parent, false);
questionRadioHolder = new QuestionRadioHolder();
questionRadioHolder.txtQuestion = (TextView) convertView.findViewById(R.id.txtQue);
questionRadioHolder.rg = (RadioGroup) convertView.findViewById(R.id.rg);
Typeface face = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-SemiBold.ttf");
questionRadioHolder.txtQuestion.setTypeface(face);
convertView.setTag(questionRadioHolder);
} else {
questionRadioHolder = (QuestionRadioHolder) convertView.getTag();
}
List<String> arrayList = rowItem.getArrayList();
questionRadioHolder.txtQuestion.setText(rowItem.getQuestionText());
questionRadioHolder.rg.removeAllViews();
questionRadioHolder.rg.clearCheck();
for (int i = 0; i < arrayList.size(); i++) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setId(i);
radioButton.setTextSize(12);
radioButton.setText(arrayList.get(i));
radioButton.setTypeface(face1);
questionRadioHolder.rg.addView(radioButton);
}
// questionRadioHolder.rg.removeAllViews();
questionRadioHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rg, int checkedId) {
for (int i = 0; i < rg.getChildCount(); i++) {
RadioButton btn = (RadioButton) rg.getChildAt(i);
ArrayList<String> list = new ArrayList<String>();
if (btn.getId() == checkedId) {
String text = btn.getText().toString();
int id = mList.get(position).getQuid();
System.out.println(position + " position 2");
map.put(id, text);
list.add(0, text);
aMap1.put(id, list);
Log.d("radio", text);
Log.d("Queid:", "" + id);
return;
}
}
}
});
} else if (type == TYPE2) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.checkbox_layout, parent, false);
questionCheckboxHolder = new QuestionCheckboxHolder();
questionCheckboxHolder.txtQuestionChk = (TextView) convertView.findViewById(R.id.chkQues);
questionCheckboxHolder.relativeLayout = (LinearLayout) convertView.findViewById(R.id.chkrl2);
Typeface face = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-SemiBold.ttf");
face1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/Raleway-Regular.ttf");
questionCheckboxHolder.txtQuestionChk.setTypeface(face);
convertView.setTag(questionCheckboxHolder);
} else {
questionCheckboxHolder = (QuestionCheckboxHolder) convertView.getTag();
}
List<String> arrayList = rowItem.getArrayList();
questionCheckboxHolder.txtQuestionChk.setText(rowItem.getQuestionText());
questionCheckboxHolder.relativeLayout.removeAllViews();
for (int i = 0; i < arrayList.size(); i++) {
checkBox = new CheckBox(getContext());
checkBox.setId(i);
checkBox.setMinHeight(30);
checkBox.setMinimumWidth(30);
checkBox.setText(arrayList.get(i));
checkBox.setTypeface(face1);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (Integer) buttonView.getTag();
ArrayList<String> arraylist2 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
int id = mList.get(position).getQuid();
arraylist2 = aMap1.get(id);
System.out.println(arraylist2);
if (arraylist2 == null) {
arraylist2 = list;
}
if (buttonView.isChecked()) {
arraylist2.add(buttonView.getText().toString());
aMap1.put(id, arraylist2);
} else {
arraylist2.remove(buttonView.getText().toString());
aMap1.put(id, arraylist2);
}
System.out.println(aMap1.get(id));
}
});
questionCheckboxHolder.relativeLayout.addView(checkBox);
}
}
return convertView;
}
If i scroll the listview, its automatically unchecked the checkbox, how can checked the checkbox.
Try this way this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelCls> listData;
public CustomAdapter(Context mainActivity, List<ModelCls> 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).getLISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelCls item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
and if you want to recyclerview try this
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
Save your check list in ArrayList<Boolean>, and load it in getView():
ArrayList<Boolean> listCheck;
public YourAdapter(Context context, int resource, ArrayList<T> list) {
super(context, resource, list);
listCheck = new ArrayList<Boolean>;
for (int i = 0; i < list.size(); i++) {
listCheck.add(false); // init listCheck
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
yourCheckBox.setChecked(listCheck.get(position)); // set checkbox
yourCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listCheck.set(position, isChecked); // update listChecked
}
}
}
If you checked on checkbox, you can save it into a HashMap(key:position, value:true/false), and in method getView() you can distinguish which is checked or unchecked, then make the checkbox show its state.
Try Using a model class or array to keep the values of checkbox and update it on onclick if that checkbox may solve your issue I think.
holder.checkBox.setChecked(mCheckList.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCheckList.set(position, !mCheckList.get(position));
notifyDataSetChanged();
}
});

Listview with checkbox bug android

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.

How to hide/show all checkbox in a listview?

I'm trying to do a listview like some android explorer, which if you make a long click on an item a checkbox appear in all rows.
I have the next Adapter, and the next code in my fragment, it do it, but for some reason, one row is not changing.
public class MultiListAdminTiemposAdapter extends ArrayAdapter<MultiListAdminTiempos> {
ArrayList<MultiListAdminTiempos> multiListAdminTiemposArrayList;
LayoutInflater mLayoutInflater;
private Context mContext;
public MultiListAdminTiemposAdapter(Context context, int textViewResourceId, ArrayList<MultiListAdminTiempos> multiListAdminTiemposArrayList) {
super(context, textViewResourceId, multiListAdminTiemposArrayList);
this.multiListAdminTiemposArrayList = multiListAdminTiemposArrayList;
this.mContext = context;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public ArrayList<MultiListAdminTiempos> getSelectedList() {
return this.multiListAdminTiemposArrayList;
}
private class ViewHolder {
private TextView tv_name, tv_tarea, tv_hours;
private CheckBox chk_tiempo;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.listview_admin_tiempos, null);
holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
holder.tv_tarea = (TextView) convertView.findViewById(R.id.tv_tarea);
holder.tv_hours = (TextView) convertView.findViewById(R.id.tv_hours);
holder.chk_tiempo = (CheckBox) convertView.findViewById(R.id.chk_tiempo);
holder.chk_tiempo.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
MultiListAdminTiempos item = (MultiListAdminTiempos) checkBox.getTag();
item.setSelected(checkBox.isChecked());
for(int i = 0; i < multiListAdminTiemposArrayList.size(); i++){
Log.e("CHK_T", "" + multiListAdminTiemposArrayList.get(i).getId() + "::" + multiListAdminTiemposArrayList.get(i).isSelected());
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MultiListAdminTiempos item = multiListAdminTiemposArrayList.get(position);
holder.tv_name.setText(item.getProject_name());
holder.tv_tarea.setText(item.getTask_name());
holder.tv_hours.setText(parseTime(item.getHours()));
holder.chk_tiempo.setChecked(item.isSelected());
holder.chk_tiempo.setTag(item);
return convertView;
}
public String parseTime(int min) {
int hours = min / 60; //since both are ints, you get an int
int minutes = min % 60;
String lb_hour = (hours == 1 ? mContext.getResources().getString(R.string.HORA_STRING) : mContext.getResources().getString(R.string.HORAS_STRING));
String lb_minute = (minutes == 1 ? mContext.getResources().getString(R.string.MINUTO_STRING) : mContext.getResources().getString(R.string.MINUTOS_STRING));
String time = "";
time += hours + " " + lb_hour;
if (minutes > 0) {
time += "\n" + minutes + " " + lb_minute;
}
return time;
}
}
My listview code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_admin_tiempos, container, false);
setHasOptionsMenu(true);
list_admin_tiempos = (ListView) view.findViewById(R.id.list_admin_tiempos);
list_admin_tiempos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (selecting) {
CheckBox chk = (CheckBox) view.findViewById(R.id.chk_tiempo);
changeCheckBoxState(chk);
/*
if (areAllUnchecked(parent)) {
for (int i = 0; i < parent.getCount(); i++) {
parent.getChildAt(i).findViewById(R.id.chk_tiempo).setVisibility(View.INVISIBLE);
}
selecting = false;
}*/
}
else {
//Vamos al detalle
viewDetail(position);
}
}
});
list_admin_tiempos.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (!selecting) {
MenuItem item = menu.findItem(R.id.action_delete);
item.setVisible(true);
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).findViewById(R.id.chk_tiempo).setVisibility(View.VISIBLE);
}
//changeCheckBoxState( ((CheckBox) view.findViewById(R.id.chk_tiempo)));
selecting = true;
}else if (selecting) {
MenuItem item = menu.findItem(R.id.action_delete);
item.setVisible(false);
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).findViewById(R.id.chk_tiempo).setVisibility(View.GONE);
}
//changeCheckBoxState( ((CheckBox) view.findViewById(R.id.chk_tiempo)));
selecting = false;
}
return true;
}
});
return view;
}
Screenshot, when I scroll down the list:

Android : Check-box issue in Grid-View

I'm trying to delete multiple selected images from Grid View.Images are deleted proper way but check box was appear as it is grid-view on Button click event.Can someone help me for solve this issue.Thanks in advance.
Here is my Code deletion
class GridView_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
SparseBooleanArray mSparseBooleanArray;
public GridView_Adapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSparseBooleanArray = new SparseBooleanArray();
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for(int i=0;i<fileName.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(fileName.get(i));
}}
return mTempArry;
}
public int getCount() {
return fileName.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.add_post_grid_item_layout, parent , false);
holder.image = (ImageView) convertView.findViewById(R.id.image);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Bitmap myBitmap = BitmapFactory.decodeFile(fileName.get(position));
holder.image.setImageBitmap(myBitmap);
final int pos = position;
holder.checkbox.setTag(position);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
int pos = (Integer) buttonView.getTag();
if (!buttonView.isChecked())
{
picsName.remove((String) fileName.get(pos));
}
else if(buttonView.isChecked())
{
if (!picsName.contains((String) fileName.get(pos)))
{
picsName.add((String) fileName.get(pos));
}
}
notifyDataSetChanged();
}
});
return convertView;
}
class ViewHolder
{
ImageView image;
CheckBox checkbox;
int id;
}
}
And here is delete button
imgDeleteImagesFromGallery = (ImageView) findViewById(R.id.imgDeleteImage);
if(gridAdapter.getCheckedItems()!= null )
{
selectedItems = gridAdapter.getCheckedItems();
if(selectedItems != null )
{
imgDeleteImagesFromGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(selectedItems.size() > 0)
{
Toast.makeText(AddPost.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
Log.e(AddPost.class.getSimpleName(), "Selected Items: " + selectedItems.toString());
Iterator it = picsName.iterator();
while (it.hasNext())
{
strFilePath = it.next().toString();
Log.e("strFilePath ", " strFilePath = " + strFilePath);
File file = new File(strFilePath);
if (file.exists())
{
boolean result = file.delete();
Log.e("File deleted ", " From classnkk_images = " + result);
}
}
gridAdapter.notifyDataSetChanged();
int countImg = gridAdapter.getCount();
textTotalImages.setText(Integer.toString(countImg));
}
}
});
}
}

how to created a variable numer elements in listview android

I'm trying to make a listView that display a question witt a variable numbers of checkBoxs. I'm using a class that extends BaseAdapter. My problem come when the list need to scroll and then get rows repeated. I know where is my error but I cant get a solution. I need to extract part of the code out of the metod getView, like I did in title of the question but I cant make for the rest, Please help.
private class AdaptadorListaPreguntas extends BaseAdapter{
ArrayList<String> array;
public AdaptadorListaPreguntas(ArrayList<String> lista){
array=lista;
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return array.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HolderListaPreguntas holder;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String frase = array.get(position);
if (convertView == null)
{
holder = new HolderListaPreguntas();
convertView = inflater.inflate(R.layout.lista_multiple_eleccion, parent, false);
convertView.setTag(holder);
//Count how many checkbox i need
for (int i=0 ; i<frase.length(); i++){
if (frase.charAt(i) == '\n'){
nCheckBox++;
}
}
//Rest one, need for the format of the string
nCheckBox--;
for(int i=0; i<nCheckBox; i++){
CheckBox cb = new CheckBox(getApplicationContext(),null,android.R.attr.checkboxStyle);
cb.setTextColor(Color.BLACK);
cb.setButtonDrawable(R.drawable.checkbox_multiple_eleccion);
//Put checkbox in to layout
holder.layout = (LinearLayout) convertView.findViewById(R.id.checkboxmultiple);
holder.layout.addView(cb);
}
//reset for next loop
nCheckBox = 0;
}
else{
holder = (HolderListaPreguntas) convertView.getTag();
}
holder.tituloPregunta = (TextView) convertView.findViewById(R.id.titulopreguntamultple);
holder.id = position;
holder.layout = (LinearLayout) convertView.findViewById(R.id.checkboxmultiple);
//Get text for each CheckBox
int indice = frase.indexOf("-");
String titulo = frase.substring(frase.indexOf(")")+1, frase.indexOf("-", indice+1));
holder.tituloPregunta.setText(titulo);
//Put all elements of layout in array
ArrayList<View> respuestas = holder.layout.getTouchables();
//Format of the text (only need "question") -Question;/;(id:n)(vof)
int indPriPreInit = frase.indexOf("-", frase.indexOf("-")+1);
int indPriPreFin= frase.indexOf(";/;");
//put text in the checkbox
for (View cb : respuestas){
if(cb instanceof CheckBox){
indPriPreInit = frase.indexOf("-", indPriPreInit);
indPriPreFin = frase.indexOf(";/;", indPriPreFin);
if (indPriPreInit > -1 && indPriPreFin > -1){
String textoCheckBox = (String) frase.subSequence(indPriPreInit, indPriPreFin);
indPriPreInit = indPriPreInit+1;
indPriPreFin = indPriPreFin+1;
//Relleno el texto del checkbox
((CheckBox) cb).setText(textoCheckBox);
}
}
}
return convertView;
}
}
public class AdaptadorListaPreguntas extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private final ArrayList<String> array;
private final List<Set<Integer>> checked;
public AdaptadorListaPreguntas(ArrayList<String> lista){
array=lista;
checked = new ArrayList<Set<Integer>>(lista.size());
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return array.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HolderListaPreguntas holder;
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String frase = array.get(position);
int checkboxCount = frase.split("\n").length-1;
if (convertView == null) {
holder = new HolderListaPreguntas();
convertView = inflater.inflate(R.layout.lista_multiple_eleccion, parent, false);
holder.layout = (LinearLayout) convertView.findViewById(R.id.checkboxmultiple);
convertView.setTag(holder);
}
else{
holder = (HolderListaPreguntas) convertView.getTag();
}
Set<Integer> current;
try {
current = checked.get(position);
} catch(NullPointerException e) {
current = new HashSet<Integer>(checkboxCount);
checked.set(position, current);
}
List<CheckBox> respuestas = new ArrayList<CheckBox>(checkboxCount);
holder.layout.removeAllViews();
for(int i=0; i < checkboxCount; i++) {
CheckBox cb = new CheckBox(getApplicationContext(),null,android.R.attr.checkboxStyle);
cb.setTextColor(Color.BLACK);
cb.setButtonDrawable(R.drawable.checkbox_multiple_eleccion);
respuestas.add(cb);
cb.setTag(position);
if (current.contains(position))
cb.setChecked(true);
holder.layout.addView(cb);
}
holder.tituloPregunta = (TextView) convertView.findViewById(R.id.titulopreguntamultple);
holder.id = position;
holder.layout = (LinearLayout) convertView.findViewById(R.id.checkboxmultiple);
//Get text for each CheckBox
int indice = frase.indexOf("-");
String titulo = frase.substring(frase.indexOf(")")+1, frase.indexOf("-", indice+1));
holder.tituloPregunta.setText(titulo);
//Format of the text (only need "question") -Question;/;(id:n)(vof)
int indPriPreInit = frase.indexOf("-", frase.indexOf("-")+1);
int indPriPreFin= frase.indexOf(";/;");
//put text in the checkbox
for (CheckBox cb : respuestas){
indPriPreInit = frase.indexOf("-", indPriPreInit);
indPriPreFin = frase.indexOf(";/;", indPriPreFin);
if (indPriPreInit > -1 && indPriPreFin > -1){
String textoCheckBox = (String) frase.subSequence(indPriPreInit, indPriPreFin);
indPriPreInit = indPriPreInit+1;
indPriPreFin = indPriPreFin+1;
//Relleno el texto del checkbox
cb.setText(textoCheckBox);
}
}
return convertView;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (Integer)buttonView.getTag();
ViewGroup vg = (ViewGroup)buttonView.getParent();
List<View> touchables = vg.getTouchables();
int index = touchables.indexOf(buttonView);
if (isChecked) {
checked.get(position).add(index);
} else {
checked.get(position).remove(index);
}
}
}
Finally i decided to use a scrollView instead a listView, the reason is the listView use a recycle system that i dont want to use and its the problem!
I found more info of How Work a ListView in: Link
Thanks all for the help.

Categories

Resources