android : checkbox problem? - java

I'm trying to select all the checkbox in list. Why am getting particular checkbox only true. Code is : -
ListView listview = (ListView)findViewById(R.id.listview1);
for(int i=0; i < listview.getChildCount(); i++)
{
AbsoluteLayout itemLayout = (AbsoluteLayout)listview.getChildAt(i);
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
if(cb.isChecked())
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
}
Thanks in Advance.

Not sure I understand the question fully..
But I belive:
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
will always return the same CheckBox (the one with id checkBox1), even if you have multiple checkboxes in your list.

Try:
for(int i=0; i < listview.getChildCount(); i++)
{
CheckBox cb = (CheckBox)listview.getChildAt(i).findViewById(R.id.checkBox1); //if the child views are properly populated in each row item then on this particular positon ChBox will be found and instantiated
if(cb.isChecked())
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
}

You Can use this with two buttons like selectall & unselectall
public void checkallbtn_Click(View view)
{
ListView lv = (ListView)findViewById(R.id.backuplist);
CheckBox cb;
try
{
for(int i=0;i<lv.getCount();i++)
{
cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
if(!cb.isChecked())
{
cb.setChecked(true);
}
}
}catch(Exception e) {e.printStackTrace();}
}
public void uncheckallbtn_Click(View view)
{
ListView lv = (ListView)findViewById(R.id.backuplist);
try
{
for(int i=0;i<lv.getCount();i++)
{
CheckBox cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
if(cb.isChecked())
{
cb.setChecked(false);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
Hope this will help you.

Related

how do I toast the number of checked boxes in my RecyclerView?

My code below works perfect when the activity loads with all checkboxes checked, or all checkboxes unchecked, and they are checked or unchecked from that point on, but the problem is that in reality the activity might load with SOME checkboxes checked.
I suppose the key is count = 0; If I could set count to the number of checked boxes when the form loads...
This is what I have in the setOnClickListener(new View.OnClickListener() { of my adapter, works for when all checkboxes start from a checked or unchecked position:
//we want to keep track of checked boxes
int count;
count = 0;
int size = MatchingContactsAsArrayList.size();
for (int i = 0; i < size; i++) {
if (theContactsList.get(i).isSelected) {
count++;
}
}
if (count == 0) {
Toast.makeText(context_type, "count is 0!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context_type, "The count is " + count, Toast.LENGTH_SHORT).show();
}
Try this.. in your recyclerView adapter .. make public static int count variable.. and in onBindViewHolder() add the checkedChangeListener() to your checkbox
public static int count = 0; // field variable
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int
position)
{
holder.cb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
count ++;
Toast.makeText(context_type, "count is " + count,
Toast.LENGTH_SHORT).show();
}
else
{
count --;
Toast.makeText(context_type, "count is " + count,
Toast.LENGTH_SHORT).show();
}
}
});
}
you could also check all checked or not.. like this ...
if(count == 0)
{
//nothing checked
}
else if(count == mList.size())
{
//all checked
}
In your adapter dont forget to add these to remember the checked positions:-
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
Get all views and count checked checkboxes with:
int checked = 0;
for (int i = 0; i < rv.getChildCount(); i++) {
try {
CheckBox checkBox = rv.getChildAt(i).findViewById(R.id.checkbox);
if (checkBox.isChecked()) checked++;
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Toast.makeText(this, "Checked: " + checked, Toast.LENGTH_SHORT).show();
where rv is your recyclerview and R.id.checkbox is your checkbox id
It works for me but make sure adapter has created views for recyclerview.
Thanks for the help above, however I found another way which simplifies my code in the process. Useful as I am repeating this process across many activities.
In my activity I PUT the already checked boxes into sharedpreferences from the server with Gson:
//Here, we PUT the arraylist into the sharedPreferences/*
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
editorcheckedContactsAsArrayList.commit();
In my adapter I GET those values from sharedpreferences, create an arrayList called checkedContactsAsArrayList:
//we are fetching the array list checkedContactsAsArrayList, created in the activity. with this we will put a tick in the checkboxes of the selected numbers
SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(context_type);
Gson gsoncheckedContactsAsArrayList = new Gson();
String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
Type type2 = new TypeToken<ArrayList<String>>() {
}.getType();
checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
Then my onBindViewHolder
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
etc...
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
//on checkbox click
public void onClick(View v) {
//pos is the row number that the clicked checkbox exists in
Integer pos = (Integer) holder.check.getTag();
//if the checkbox is checked
if (holder.check.isChecked())
{
//we want to add the phone number of the checked row into our arraylist.
//add the checked number into the arraylist
checkedContactsAsArrayList.add(theContactsList.get(pos).getPhone());
} else {
//remove the checked number from the arraylist
checkedContactsAsArrayList.remove(theContactsList.get(pos).getPhone());
}
And also in my onBindViewHolder, no need for loops or anything:
if (checkedContactsAsArrayList.size() == 0) {
Toast.makeText(context_type, "count is 0!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context_type, "The count is " + checkedContactsAsArrayList.size(), Toast.LENGTH_SHORT).show();
}
Thanks!

How to get the id of a radio button in Java?

I've created pragmatically 5 radio groups with 4 radio buttons each. How can i get the Id of the radio buttons? Very important, i dont't want to use setOnCheckedChangeListener. Here is my code.
radioGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
radioGroup[i] = new RadioGroup(this);
radioGroup[i].setId(i);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answer[j].setId(j);
radioGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
answer[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int checkedRadioButtonId = v.getId();
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
if (checkedRadioButton.isChecked()) {
Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
}
}
});
i++;
}
Thanks!
as in log :
ArrayIndexOutOfBoundsException: length=4; index=4
Because answer Array is size of j instead of i, so move RadioButton click listener inside for loop:
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
...your code here...
answer[j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code here...
}
});
j++;
}
}

Android table row onClickListener

I am having some problems when trying to trigger events on table layout in Android. These are the codes I used to populate the table layout dynamically:
private void BuildTable() {
try {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Category.this);
mDbHelper.open();
CategoryController cc = new CategoryController(mDbHelper.open());
Cursor mCur = mDb.rawQuery(cc.getAllCat(), null);
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
// Setting table header
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
do {
int cols = mCur.getColumnCount();
row = new TableRow(this);
for (int j = 1; j < cols; j++) {
// Dynamically load data fetch from database
// into table layout
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setPadding(5, 5, 10, 5);
tv.setGravity(Gravity.LEFT);
tv.setText(mCur.getString(j));
row.addView(tv);
row.setId(j);
}
row.setClickable(true);
row.setOnClickListener(tablerowOnClickListener);
table_layout.addView(row);
} while (mCur.moveToNext());
}
}
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
And here is my table row onClickListener:
private OnClickListener tablerowOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Highlight selected row
v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
final int k = v.getId();
Toast.makeText(Category.this, Integer.toString(k),
Toast.LENGTH_SHORT).show();
}
};
My problem is when I highlighted certain row and I select another row again, the previous highlighted row remains the same highlighted background color. I wonder how to solve it?
Thanks in advance.
Provided table_layout is in the same scope as tablerowOnClickListener, change the Listener as follows:
private OnClickListener tablerowOnClickListener = new OnClickListener()
{
public void onClick(View v)
{
//Highlight selected row
for (int i = 0; i < table_layout.getChildCount(); i++)
{
View row = table_layout.getChildAt(i);
if (row == v)
{
row.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
else
{
//Change this to your normal background color.
row.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
//...
}
};

Get the ID of checkbox from custom adapter in android?

I have a Custom ArrayList as follows.
public class sendivitesadapter extends ArrayAdapter<Item>{
private Context context;
private ArrayList<Item> items;
private qrusers qrusers;
private LayoutInflater vi;
public sendivitesadapter(Context context,ArrayList<Item> items) {
super(context, 0,items);
this.context= context;
this.qrusers =(qrusers) context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
sendItem ei = (sendItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
final TextView title = (TextView)v.findViewById(R.id.contactname);
final TextView subtitle = (TextView)v.findViewById(R.id.companyname);
final CheckBox checkBox=(CheckBox)v.findViewById(R.id.checboxlist);
if (title != null)
title.setText(ei.contactname);
if(subtitle != null)
subtitle.setText(ei.companyname);
}
}
return v;
}
and it looks like following image.
My java file is as follows.
#Override
protected void onPostExecute(String result) {
JSONArray jarray;
try {
jarray= new JSONArray(result);
name= new String[jarray.length()];
company=new String[jarray.length()];
for (int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
name[i]= jobj.getString("Name");
company[i]=jobj.getString("Company");
items.add(new sendItem(name[i], company[i], checkBox));
adapter = new sendivitesadapter(qrusers.this,items);
listView.setAdapter(adapter);
Now I get the names from webservice which I am diplaying it in a listview as shown above.
With every name I get a USerID. So my question is whenever the user checks the checkbox in any sequence and click on add user I want the UserID of the checked checkboxes in array. How can I achieve this?
Sounds like it's a good candidate for View.setTag(). You could set the tag on each CheckBox to the id of the user [when you create it, or assign the Name and Company values]. Then in an OnClick or OnChecked type event, you can call view.getTag() to retrieve the id of the currently checked box.
You need to use OnCheckedChangeListener to get the cheched CheckBox ID. This SO will help you- How to handle onCheckedChangeListener for a RadioGroup in a custom ListView adapter . You need to modify the onCheckedChangeListener according to your need.
In your adapter set the position in check box like
checkBox.setTag(position);
And as i think you have to add checked user on click of Add User button. So on click of that button write following code.
public void onClick(View v) {
// TODO Auto-generated method stub
String categoryArray = "";
String[] categoryId;
if(v == AddUser){
int count = 0;
for(int i = 0; i < listViewRightSlideMenu.getChildCount(); i ++){
RelativeLayout relativeLayout = (RelativeLayout)listViewRightSlideMenu.getChildAt(i);
CheckBox ch = (CheckBox) relativeLayout.findViewById(R.id.checkBoxCategory); //use same id of check box which you used in adapter
if(ch.isChecked()){
count++;
categoryArray = categoryArray+ch.getTag()+",";
}
}
if(categoryArray.length() > 0) {
categoryArray = categoryArray.substring(0, categoryArray.length() - 1);
String[] array = categoryArray.split(",");
categoryId = new String[array.length];
for(int i = 0; i< array.length; i++) {
categoryId[i] = listCategory.get(Integer.valueOf(array[i])).getId();
}
for(int i = 0; i < categoryId.length; i++){
String a = categoryId[i];
System.out.println("category id is: "+a);
}
System.out.println("array position: "+categoryId);
}
}

onClickListener onclicklistener Android Java programming

When i click on the images it doesnt change the display textview, where did i go wrong?
**List<ImageView> fields = new ArrayList<ImageView>();
for(int i = 0; i < 64; i++) {
try{
id = R.id.class.getField("square" + (i+1)).getInt(0);
views.add((ImageView)findViewById(id));
((View) fields).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View fields) {
for(int i=0; i < 64; i++)
{
display = (TextView) findViewById(R.id.textView1);
display.setText("square" + i);
}
}
});
}
catch(Exception e){}
}**
}
}
It looks like you're adding the onClick listener to the ArrayList of views, not the image you added. Change
((View) fields).setOnClickListener
to
findViewById(id).setOnClickListener

Categories