Android dynamic check box not getting values - android

I have created a layout dynamically and added check boxes. code as follows,
//Load dynamic view
List<Integer> checkBoxIdList = new ArrayList<Integer>();
int id = 0;
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("CatchInfo");
tv.setTextColor(Color.rgb(200,0,0));
ll.addView(tv);
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setText(list2.get(i));
ll.addView(ck);
}
Button btnHome = new Button(this);
btnHome.setText("Home");
ll.addView(btnHome);
Button btnSubmit = new Button(this);
btnSubmit.setText("Submit");
ll.addView(btnSubmit);
this.setContentView(sv);
I am trying get value value of check box using click listner as follows:
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
But the click action is only taken place in last check box and in others it is not responding. How can solve this and how will I get values?

You need to create your function to handle the onCheckedChangeListener.. See the below code.
List<Integer> checkBoxIdList = new ArrayList<Integer>();
int id = 0;
String[] list2 = {"A", "B", "C", "D", "E"};
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("CatchInfo");
tv.setTextColor(Color.rgb(200,0,0));
ll.addView(tv);
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setTag(list2[i]); // set the tag values so that you can refer to them later.
ll.addView(ck);
ck.setOnCheckedChangeListener(handleCheck(ck)); //Calling the function, add this line in your code
}
Button btnHome = new Button(this);
btnHome.setText("Home");
ll.addView(btnHome);
Button btnSubmit = new Button(this);
btnSubmit.setText("Submit");
ll.addView(btnSubmit);
this.setContentView(sv);
Here is the function which handles the check events
private OnCheckedChangeListener handleCheck (final CheckBox chk)
{
return new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(!isChecked){
Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
}
};
}

You have to do like this.
for(int i=0;i<list2.size();i++)
{
CheckBox ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
ck.setText(list2.get(i));
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
ll.addView(ck);
}

you forgot to increment in id variable.
thats y all checkboxes you are adding will get same id.
List<CheckBox> checkBoxesList2 = new ArrayList<CheckBox>();
for(int i=0;i<list2.size();i++)
{
ck = new CheckBox(this);
ck.setId(id);
checkBoxIdList.add(id);
checkBoxesList2.add(ck);
id++;
ck.setText(list2.get(i));
ll.addView(ck);
}
for(int i=0;i<checkBoxesList2.size();i++){
ck =(CheckBox) checkBoxesList2.get(i);
ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(!isChecked){
Toast.makeText(getApplicationContext(), "Yes",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No",
Toast.LENGTH_LONG).show();
}
}
});
}

Related

How to uncheck all other check boxes except only one box ?

I have two check boxes in a alert dialog box. What I want is that if one of the checkbox is clicked then other checkbox gets unchecked automatically. Only one checkbox can be clicked at a time. I've searched the internet and tried multiple solutions but no solution is working.
find ids of your check boxs...
checkBoxOne= (CheckBox)findViewById(R.id.checkBox1);
checkBoxTwo= (CheckBox)findViewById(R.id.checkBox2);
checkBoxOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Here you unchecked the other check boxes
checkBoxTwo.setChecked(false);
}
}
});
checkBoxTwo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Here you unchecked the other check boxes
checkBoxOne.setChecked(false);
}
}
});
If you really want to use a CheckBox you have to programmatically uncheck the other button:
private void createCustomDialogCheckBox() {
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
final CheckBox checkBoxOption1 = new CheckBox(this);
final CheckBox checkBoxOption2 = new CheckBox(this);
checkBoxOption1.setText("Option 1");
checkBoxOption2.setText("Option 2");
checkBoxOption1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox otherCheckBox = checkBoxOption2;
if(isChecked && otherCheckBox.isChecked()){
otherCheckBox.setChecked(!otherCheckBox.isChecked());
}
}
});
checkBoxOption2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox otherCheckBox = checkBoxOption1;
if(isChecked && otherCheckBox.isChecked()){
otherCheckBox.setChecked(!otherCheckBox.isChecked());
}
}
});
dialogLayout.addView(checkBoxOption1);
dialogLayout.addView(checkBoxOption2);
dialogBuilder.setView(dialogLayout);
dialogBuilder.show();
}
A better solution is to use RadioButton with does all this automatically:
private void createCustomDialogRadioButton() {
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
RadioButton radioButtonOption1 = new RadioButton(this);
RadioButton radioButtonOption2 = new RadioButton(this);
radioButtonOption1.setText("Option 1");
radioButtonOption2.setText("Option 2");
RadioGroup radioGroup = new RadioGroup(this);
// radio buttons must be on the same radio group
// so that other buttons will automatically be unchecked / unselected
radioGroup.addView(radioButtonOption1);
radioGroup.addView(radioButtonOption2);
dialogLayout.addView(radioGroup);
dialogBuilder.setView(dialogLayout);
dialogBuilder.show();
}

Radio Button goes wrong in android

Sometimes when i want to select choices in radio buttons there is something wrong with radio buttons which i can select Two radios However sometimes is right as default way it must be worked.
Here two sample in my application :
Here's my Code :
span.replace(0,0,getText(R.string.ForeSingleChoice));
new DynamicViews().makeNormalContent(getApplicationContext(),span,linearLayout,16,16,16,16,16.0f);
span.clear();
radioGroup = new DynamicViews().makeRadioGroup(getApplicationContext(),linearLayout);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),-1);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case 5: goToNextLevel= true ;
break;
default: goToNextLevel = false;
break;
}
}
});
DynamicViews makeRadioButton:
public RadioButton makeRadioButton(Context context, RadioGroup radioGroup, String text, int Id) {
RadioButton radioButton = new RadioButton(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioButton.setBackgroundResource(R.drawable.backgroundbetweenradios);
radioButton.setLayoutParams(Params);
radioButton.setPadding(dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context));
radioButton.setId(Id);
radioButton.setText(text);
radioButton.setTextColor(Color.BLACK);
radioGroup.addView(radioButton);
return radioButton;
}
DynamicViews makeRadioGroup:
public RadioGroup makeRadioGroup(Context context, LinearLayout linearLayout) {
RadioGroup radioGroup = new RadioGroup(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(Params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
CardView cardView = new CardView(context);
cardView.setCardBackgroundColor(Color.WHITE);
cardView.setCardElevation(8.0f);
Params.setMargins(dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context));
cardView.setLayoutParams(Params);
cardView.addView(radioGroup);
linearLayout.addView(cardView);
return radioGroup;
}
My application is consists of a lot of radiobuttons ,This is the approach i've made these radio buttons , what's the problem ? is this a bug ?
Have you tried to give each radio button unique id?
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),2);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),3);
add this on your onCreate()
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
rbtn1.setChecked(yesrbtn == buttonView);
rbtn2.setChecked(norbtn == buttonView);
....
}
}
};
rbtn1.setOnCheckedChangeListener(listener);
rbtn2.setOnCheckedChangeListener(listener);
what this does is making sure that radiobuttons are not allowed to have 2 or more selection

How to check RadioButton is checked when added dynamically?

In my application I am adding RadioButton dynamically depending on requirement.
Below is the code :
RadioGroup rg = new RadioGroup(StartExamActivity.this);
View v = new View(StartExamActivity.this);
v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
v.setBackgroundColor(Color.parseColor("#3593D4"));
rg.setLayoutParams(new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
rg.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < list.size(); i++) {
rdbtn[i] = new RadioButton(StartExamActivity.this);
rdbtn[i].setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, 1f));
rdbtn[i].setId(i);
rdbtn[i].setText(list.get(i));
final String value = rdbtn[i].getText().toString();
rdbtn[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (value.equalsIgnoreCase(answer)) {
marks = marks + 2;
}
}
});
rg.addView(rdbtn[i]);
}
questionContainer.addView(rg);
Now I want to increase the value of marks by 2 only ones even when RadioButton is checked multiple times. For that I want to know whether RadioButton is checked or not.
How to do this??
Please Help!!
Simple thing,
Why don't you use OnClickListener instead of onCheckedChanged>
rdbtn[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked) {
// Write your logic here...
}
});

how to update item in tablelayout after row selected?

I have TableLayout with 2 buttons and some textView
I added rows dynamically from sq-lite with these codes and it works:
TableLayout tbl
= (TableLayout) Vfood.findViewById(R.id.frag_food);
///
///somecode
///
dbfood.open();
Cursor cursor = dbfood.getGroupFood(group_Name);
int i = 1;
if (cursor.moveToFirst()) {
do {
TableRow tr = new TableRow(getActivity());
tr.setId(i);
//btnAdd
final Button btnAddDeser = new Button(getActivity());
btnAddDeser.setText("add");
btnAddDeser.setId(i);
TableRow.LayoutParams trParams1
= new TableRow.LayoutParams(65, TableRow.LayoutParams.MATCH_PARENT);
btnAddDeser.setGravity(Gravity.LEFT);
btnAddDeser.setTextSize(10);
btnAddDeser.setPadding(30, 10, 10, 10);
btnAddDeser.setMaxWidth(65);
btnAddDeser.setMinimumWidth(70);
//my problem>
btnAddDeser.setOnClickListener(mListener);
//
tr.addView(btnAddDeser, trParams1);
// Count
final TextView trCount = new TextView(getActivity());
trCount.setText(cursor .getString(3));
trCountDeserc.setId(i);
trCount.setTextColor(Color.BLACK);
trCount.setGravity(Gravity.RIGHT);
trCount.setTextSize(10);
trCount.setPadding(10, 10, 10, 15);
trCount.setClickable(true);
tr.addView(trCount);
///
///other text View
///some code
tbl.addView(tr,
new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
i++;
} while (cdeser.moveToNext());
}
dbDeser.close();
return Vfood;
}
private OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
//
//I dont know what shoud i do !
//
}
};
I just want to increase trCount one digit when user click on button.
can anyone help me?
I am new to android.
thanks
You just add this Button click event in your loop
btnAddDeser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String str=trCount.getText().toString();
Toast.makeText(getActivity(), str, Toast.LENGTH_LONG).show();
}
});

Create and validate check box programmatically using Java in Android

I need to create a number of check boxes programmatically using Java, check if one of them is checked and when I click Next Button the control will move to next page. If none of them is checked a toast message has to be displayed. Please suggest as I am new to Android.
Here is my code:
public class TestValidCheckboxActivity extends Activity implements OnCheckedChangeListener{
private RelativeLayout layoutMiddle = null;
private TableLayout layout1;
private CheckBox chk;
private String[] resarr = {"silu", "pinky", "meera"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layoutMiddle = (RelativeLayout)findViewById(R.id.layoutMiddleUp);
layout1 = (TableLayout)findViewById(R.id.tableId1);
final Button btnNext = (Button)findViewById(R.id.btnNext);
int i = 0;
for(String res: resarr){
TableRow tr=new TableRow(this);
chk=new CheckBox(this);
chk.setId(i);
chk.setText(res);
chk.setTextColor(Color.BLACK);
tr.addView(chk);
i++;
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lay.addRule(RelativeLayout.BELOW, layoutMiddle.getId());
layout1.addView(tr, lay);
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if (arg1)
{
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
Log.e("1111111111","111111111");
if(chk.isChecked()){
Intent intent = new Intent(view.getContext(),NextPage.class);
startActivityForResult(intent, 0);
}else{
Toast msg = Toast.makeText(view.getContext(), "please choose at least one option", Toast.LENGTH_LONG);
msg.show();
}
}
});
}else{
Toast msg = Toast.makeText(TestValidCheckboxActivity.this, "please choose at least one option", Toast.LENGTH_LONG);
}
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
this can be easily done
take a boolean flag and set true it on checkbox.isChecked();(inbuilt)
then check if flag is set then navigate to next else TOAST
Can you show us some of your layout code, meaning, are the checkboxes defined in an xml file and do they have IDs?
If they do, you can access each of them with findViewByID and check their status one by one.

Categories

Resources