Get text of selected checkboxes android? - android

I have 5 checkboxes in my activity xml. I need to get the text of all the selected checkboxes.
One approach is to see if checkbox1 ischecked() and get the text.
if(checkbox1.isChecked())
{ String text=checkbox1.getText().toString();}
and so on.
This becomes quite a lengthy process.
Is there any other approach I can use?

A couple of basic suggestions:
You do not need to ==true operation above so a simple if(checkbox1.isChecked()) would suffice.
Store them all in an ArrayList so you can iterate as below:
List<CheckBox> items = new ArrayList<CheckBox>();
for (CheckBox item : items){
if(item.isChecked())
String text=item.getText().toString();
}

CheckBox[] nameString = new CheckBox[]{Array1, Array2, Array3, Array4, Array5, Array6, Array7, Array8};
for (int i=0; i<=7; i++)
{
if (nameString[i].isChecked())
{
Toast.makeText(getApplicationContext(), nameString[i].getText().toString(), Toast.LENGTH_SHORT).show();
}
}

Rather than looping through all your checkBoxes to find which one of them is checked, you could simply create a List of selected items at onCHeckedChanged() or onClick()
If(unChecked)==>Add to List==> if(Checked) ==> Remove from list

Kotlin sample code:
You can create an event and bind same event to all the check boxes, like
<CheckBox
android:id="#+id/chk1"
android:onClick="onCheckBoxClicked" ....
<CheckBox
android:id="#+id/chk2"
android:onClick="onCheckBoxClicked" ....
MainActivity:
fun onCheckBoxClicked(view:View){
view as CheckBox
if (view.isChecked){
var msg = view.text.toString()
Log.d("Checkbox", msg) //printing in log
}

Related

Get getCheckedItemPositions() and getCheckedItemIds() always returns null

I have a listview in an android app with checkboxes and I'm trying to get a list of the items that are checked. I have tried both setting the checked state in the getView() method with setChecked(true) and by checking it manually by tapping on the item. I've tried two different methods for getting the checked items and both return null. What am I doing wrong?
Greg
//Called from a menu
//First attempt - checked is always null
//I also set setChoiceMode = CHOICE_MODE_MULTIPLE before setting adapter
//and set no setChoiceMode
String ItemsChecked = null;
ListView listview = (ListView) findViewById(R.id.ListLists);
SparseBooleanArray checked = listview.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if (checked.get(i)) {
ItemsChecked += Integer.toString(i) + ",";
}
}
//I then tried this and checked[] is empty
//I also set setChoiceMode = CHOICE_MODE_NONE before setting adapter
long checked[] = listview.getCheckedItemIds();
for (int i = 0; i < checked.length; i++) {
ItemsChecked += "" + checked[i] + ",";
}
//Layout for the ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="4dp"
android:src="#drawable/ic_listit" >
</ImageView>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="22sp" >
</TextView>
</LinearLayout>
I am not sure you have provided enough information to solve the problem. But here are some troubleshooting steps that may help point you in the right direction:
1) Instead of getting an array based on the number of checked items in the listView, see if you can pull the array of items in the entire list, or at least the first 100 if the list is very large. Then output the index number of each item in a string like you had in your first attempt. You could also try and output whether the current item is checked or not.
this will tell you if you have a populated list to pull from. If you don't, well there's your problem.
2) I would also check to make sure that your listView's name is also correct. I would assume the compiler would catch this but you never know.
3) Finally, I can't see where or how the list is populated. It may be a good idea to check and see the rest of the code to see if maybe something is happening somewhere else.
Sorry if this is not particularly helpful. If all of this checks out and the problem is not being created in one of those areas this link may help:
Android: list.getCheckedItemPositions() always returns null
Good Luck and I hope this helps a little.
Max,
Well, you pointed me in the right direction for a 'solution'. This may not be the proper way to do it, but given this is my my first android app, I am ready to move on after spending the entire morning trying to get a list of just those items that are checked with a built-in method. I modified code from the link you posted and came up with the code below. It seems to work.
I wonder if I will have problems with lists that don't show everything at once. My test only has two items in the list. If items are checked and then scrolled out of view, will this work. More testing needs to be done.
Thanks,
Greg
ListView listview = (ListView) findViewById(R.id.ListLists);
View v;
CheckBox ck;
TextView tv;
for (int i = 0; i < listview.getCount(); i++) {
v = listview.getChildAt(i);
ck = (CheckBox) v.findViewById(R.id.checkBox1);
tv = (TextView) v.findViewById(R.id.label);
if (ck.isChecked()) {
Toast.makeText(getApplicationContext(), tv.getText() + "Checked" , Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(getApplicationContext(), tv.getText() + "Not checked" , Toast.LENGTH_LONG)
.show();
}
}

How to get dynamic CheckBox Id

I have created checkbox dynamically. Based on the require list size just am creating new dynamic check box in a repeated manner and am also setting the Id for that. Now i want to do check it in other loop.
for(int i=0;i<require.size();i++)
{
//From Requirements
requirement=require.get(i);
RelativeLayout rl1 = new RelativeLayout(getActivity());
rl1.setBackgroundResource(R.drawable.listviewdesign);
l1.setOrientation(LinearLayout.VERTICAL);
req1 = new CheckBox(getActivity());
rl1.addView(req1);
req1.setId(Integer.parseInt(requirement.r_id));
Log.i("getid",Integer.toString(req1.getId()));
li.add(Integer.toString(req1.getId()));
}
In this loop am just checking element of li and proj_require1 values. If both are equal then I want to make the CheckBox as checked. For that i have written the code here.
for(int i=0;i<li.size();i++)
{
//li.get(i);
req1 = (CheckBox) container.findViewById(i);
String sr = req1.toString();
for(int j=0;j<proj_require1.size();j++)
{
pr = proj_require1.get(j);
if(sr.equals(pr.rid))
{
req1.setChecked(!req1.isChecked());
}
else
{
req1.setChecked(req1.isChecked());
}
}
}
But my doubt is in first loop am creating the CheckBox based on the size of require object. So every time it creates the CheckBox inside the loop. But in second loop am trying to access the checkbox which am created in the first loop. Could anyone please help me to solve this problem? The only way is i can create the CheckBox in the first loop. I want to access it in other loop. Is it possible?

swithcing to next textview

Ok im making app and it have 15 button's and 6 textview's.I want when I press first button to change value of first textview(value is "") to something (number one for example).But problem is when i press second button if first textview is already set to some value to set set second textview to second value.
If you need something else ask in comments (sorry for bad English)
here is what I was doing(this is under onclick)when i press second button
if(textview1.equals("1")){
textview2.setText("2");}
else if (textview1.equals("")){
textview1.setText("2");
}
It sounds like you wish to show last 6 buttons pressed.
Store all pressed buttons in a List (i.e. LinkedList) of size 6. Initially, it will be empty.
Then whenever any button is pressed do two things:
1) add it to the List and delete old elements if size exceeds six.
2) set button values from List.
Second step can be achieved like this:
// all TextViews should be in a list
private List<TextView> textViews;
// declare as field
private List<String> memoryQueue = new ArrayList<String>();
public void update() {
//set fields for the pressed buttons
for (int i=0; i<6 && i<memoryQueue.size(); i++) {
String text = memoryQueue.get(i);
textViews.get(i).setText(text);
}
// set empty fields
for (int i = memoryQueue.size(); i<6; i++) {
textViews.get(i).setText("");
}
}
This code snippet assumes that you store your TextViews in a List.
And Easiest way to keep track of last six button:
public void buttonPressed(Button button) {
//get text based on your button
String text = button.getText();
if (memoryQueue.contains(text)) {
return;
}
memoryQueue.add(text);
if (memoryQueue.size() > 6) {
memoryQueue.remove(0);
}
}
Since you're concerned with the text inside of your text view, you should be using the object's getText method:
if( textview1.getText().equals("1") ){ // Edited
textview2.setText("2");
} else if (textview1.getText().equals("")){ //Edited
textview1.setText("2");
}
At first, you have to get the String text from TextView using getText() method then you can compare that String with another String. Now, change your condition as follows...
if(textview1.getText().toString().equals("1")){
textview2.setText("2");}
else if (textview1.getText().toString().equals("")){
textview1.setText("2");
}

How to select one checkbox at time in customized listview in android

after the lot of try , i did not find the solution how to select the one checkbox at a time in customized list view in android. the data come dynamically through the web service . if i select on one check box in list view and other are uncheck . If any buddy have solution please share with me.
In click of every check box call notifyDatasetChanged with your adapter and then make it selected .
You can refer to this Unable to check/uncheck CheckedTextView inside getView ,this post is little different form what you need but it can help you.
Add Below line in your xml file in all radiobutton:
<RadioButton
...
android:onClick="onClickRadioButton"
...
/>
then put below code in your java file:
private RadioButton listRadioButton = null;
int listIndex = -1;
public void onClickRadioButton(View v) {
View vMain = ((View) v.getParent());
if (listRadioButton != null) listRadioButton.setChecked(false);
listRadioButton = (RadioButton) v;
if (listRadioButton.isChecked) {
listIndex = ((ViewGroup) vMain.getParent()).indexOfChild(vMain);
} else {
listRadioButton = null;
listIndex = -1
}
}

How to manage onclick on dyanamically generated checkbox in android

I have created multiple checkboxes via applying looping.
for(int l=0;l<len;l++)
{
chkBox = dynamicUiComponents.myCheckBox(context, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT), 100+i, "Unchecked", opts[l]);
myLayout.addView(chkBox);
}
All the check boxes are showing. But when I am applying setOnCheckedChangeListener(l) on that check box, then only last added check box text is printer. Its because every time in loop, I provide a new object reference to the chkBox variable. So here how to identify that which chechbox is clicked.
In your code, you did not create an array of CheckBoxes, you only created one. So, using setOnCheckChangedListener(I) will not refer to the checkBox. Either you set the listener inside the loop, or give each a unique ID to refer to it later and set the listener:
for(int l=0;l<5;l++) { chkBox = new CheckBox(context);
chkBox.setOnCheckChangedListener(
//your implementation
);
myLayout.addView(chkBox); }
you can add id to tag:
for(int id=0;id<5;id++) {
chkBox = new CheckBox(context);
chkBox.setTag(id);
myLayout.addView(chkBox);
}
and you may use:
Integer i = (Integer) chkBox.getTag();
Try the following
for(int l=0;l<5;l++)
{
chkBox = new CheckBox(context);
myLayout.addView(chkBox);
chkBox.setTag(""+l);
chkBox.setOnCheckChangeListener(new ...(){
int x = Integer.ValueOf(chkBox.getTag());
//do whatever you want to do here
});
}
You can set a different tag for each Checkbox and set the listener on THIS, you activity should implement the listener and then do whatever you want when the event is trigger.

Categories

Resources