Hi I am making some sort of quiz application and I want to make sure the user checks at least 1 check box.
I am creating the the check boxes like this:
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i < question.length ; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
int flag = 0;
if(box.isChecked() == true)
{
flag = 1;
}
if(flag == 1)
{
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();
}
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
But I cant figure out how to make sure the user has checked at least 1 box.
Maybe you can try this method?
private boolean checkSelectionExists() {
boolean selectionExists = false;
selectionExists = (boolean) ((CheckBox) findViewById(R.id.main_checkbox1)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox2)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox3)).isChecked() ? true : false;
return selectionExists;
}
Add your checkboxes to a list as you create them. then use the
checkbox.isChecked()
routine in a loop to make sure at least 1 is checked.
Look here for the checkbox API
http://developer.android.com/reference/android/widget/CheckBox.html
and here for a list:
http://developer.android.com/reference/java/util/List.html\
// Added List
List<Checkbox> ansList = new List<Checkbox>();
// YOUR CODE with the list addition
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++){
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
// Since a test, make sure no answer is checked
box.setChecked(false);
// Add the checkbox to YOUR list of boxes
ansList.add(box);
mLinearLayout.addView(box);
}
}
}
// Later you can check with this
boolean atLeastOne = false;
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
for(int zed = 0; zed < question[i].answers.length; zed++){
if(ansList.get(zed).isChecked()) atLeastOne = true;
}
}
}
if(true == atLeastOne){
// Do whatever you want to do if at least one is checked
}
I have NOT actually run or checked this code, but this should get you started, and it SHOULD work.
I am giving a quick logic that come after reading your question,
create a class level boolean variable named isCheckButtonClicked
set by default its value to false
Now on each checkbox's click event set its value to true
Now at the final if you found it's value to true that means atleast one checkbox was cliked
Just make a flag and check every time, if a check-box is true make it = "1"and at last check whether it is "1" or not
Something like
Box[0]=name_of_first_Checkbox;
Box[1]=name_of_second_Checkbox;
// and so on..
int flag = 0;
for (int i = 0; i < x ; i++){
if(Box[i].isChecked())
{
flag =1;
}
}
if(flag==1){
//At least 1 box is checked
}
Related
I want to save all the selected answer(checkbox and radiobutton) and its corresponding question which is set in dynamic Textview in sqlite db ,
but the problem is when i am clicking "save button" only last selected
radio button value is saved to sqlite , not all selected value and not able to get all selected check box value also .
Please help me .
save= (Button) findViewById(R.id.save);
save.setOnClickListener(this);
ll = (LinearLayout) findViewById(R.id.linearLayout1);
for (int j = 0; j < Questions.length; j++) {
tv = new TextView(this);
tv.setId(j);
tv.setText(Questions[j].getQuestionNo() + "."
+ Questions[j].getQuestion());
ll.addView(tv);
Answer[] answer = Questions[j].getAnswer();
if (Questions[j].getMultipleChoice().equalsIgnoreCase("false")) {
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
RadioButton[] rb = new RadioButton[answer.length];
for (int i = 0; i < answer.length; i++)
{
// add radio buttons
rb[i] = new RadioButton(this);
rb[i].setText(answer[i].getLabel());
int id = Integer.parseInt(j + "" + i);
rb[i].setId(id);
rg.addView(rb[i]);
}
ll.addView(rg);
else
{
// add checkboxes
for (int i = 0; i < answer.length; i++) {
cb = new CheckBox(this);
cb.setText(answer[i].getLabel());
int id = Integer.parseInt(j + "" + i);
cb.setId(id);
ll.addView(cb);
}
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.save:
if (rg.getCheckedRadioButtonId() != -1) {
int id = rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(id);
int radioId = rg.indexOfChild(radioButton);
RadioButton btn = (RadioButton) rg.getChildAt(radioId);
String answer = (String) btn.getText();
//only last selected radio button value is coming
}
// not able to get all the selected checkbox value
break;
default:
break;
}
}
I don't know android.But the issue arise me in struts2.I solved that issue by generating dynamic checkbox like below.
<s:iterator value="samplelist">
<input type="checkbox" value="true" style="margin-top:2px;" name="p_<s:property value='profileId'/>
</s:iterator>
so i have found out if it is checked or not in java code by using the for loop
for(int i=0;i<samplelist.size();i++)
request.getParameter("P_something");
As you can see below, I am dynamically creating some sort of quiz with different types of questions (RadioButtons and CheckBoxes).
So I can generate them correctly and they appear as they should.
At the end of the questions there is a normal Button.
And I want to make it available for click only after all the questions have been answered.
I have a function to make sure that all the RadioButtons are answered.
But since I have two types of buttons I can't figure out how to make sure that the questions with the CheckBox answers have at least 1 checked answer.
I have the following code:
ArrayList<RadioGroup> arrGroup;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button) findViewById(R.id.button1);
buttHole.setEnabled(false);
getQuestions();
//Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i <= question.length; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean checkQuestionsAnswer()
{
int count = arrGroup.size();
for (int i = 0; i < count; i++)
{
if (arrGroup.get(i).getCheckedRadioButtonId() == -1)
{
Toast.makeText(getApplicationContext(), "Not all questions are answered!", Toast.LENGTH_SHORT).show();
return false;
}
}
Toast.makeText(getApplicationContext(), "Thank you!", Toast.LENGTH_SHORT).show();
buttHole.setEnabled(true);
//Return true if all answer are given
return true;
}
If you have less than 10 answers per question set the id of the checkboxes to (i*10)+zed for example. This way you could loop through the answers like this
for(int i=0; i<question.length; i++){
boolean questionAnswered = false;
for(int zed = 0; zed < question[i].answers.length; zed++) {
CheckBox box = (CheckBox) findViewById(i*10+zed);
if(box != null && box.isChecked()) {
questionAnswered = true;
...
}
}
}
I didn't try this code, and it's just a quick and dirty hint, but I hope it helps.
I have 3 row in table, where every row has 3 checkbox. I want to check appropriate CheckBox according to its id.
I have to check following ids CheckBox.
tempArray =[1-2-3,3-2,null];
i am already splitting these data and putting in string array(setopts).more see my code.
Null for no check any CheckBox with this row.
I am doing this code in my project.
Vector<CheckBox> chkBoxList = new Vector<CheckBox>();
Vector<TextView> txtViewList = new Vector<TextView>();
// mat_elemItemSetChk.get(0).size() OF VALUE IS 3
for (int n = 0; n < mat_elemItemSetChk.get(0).size(); n++) {
LinearLayout llayout = new LinearLayout(getContext());
ll.setOrientation(android.widget.LinearLayout.VERTICAL);
cb = new CheckBox(getContext());
tv = new TextView(getContext());
for (int r = 0; r < tempArray.size() ; r++) {
isContains=tempArray.get(r).contains(individualValueSeparator);
if(isContains){
setOpts = tempArray.get(r).split("\\-");
for (int k = 0; k < setOpts.length; k++)
{
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) iv.getId()) == Integer.parseInt(setOpts[k]))
{
mat_elemItemSetChk.get(n).get(Integer.parseInt(setOpts[k])-1);
cb.setChecked(true);
}
}
}else{
if(tempArray.get(r).toString().equalsIgnoreCase("null")||tempArray.get(r).toString()!=null){
String temp;
String px[]= null;
temp = tempArray.get(r).toString();
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) IV.getId()) == Integer.parseInt(temp))
{
mat_elemItemSetChk.get(0).get(Integer.parseInt(temp) - 1);
cb.setChecked(true);
}
}else{
cb.setChecked(false);
}
}
}
tv.setText(mat_elemItemSetChk.get(0).get(n) .toString());
llayout.addView(cb);
llayout.addView(tv);
chkBoxList.add(cb);
txtViewList.add(tv);
ll.addView(llayout);
// this.addView(tableLayout);
}
Thank you in advance.
make an array selchkboxlist and store the selected checkbox id in it and check condition like selchkboxlist.isEmpty() if true then then show error msg other wise go ahed...
selchkboxlist=new ArrayList<String>();
cbs = new CheckBox[8];
// generate dynamic item check box code
for(int k = 0; k<8; k++)
{
cbs[k] = new CheckBox(getApplicationContext());
#SuppressWarnings("deprecation")
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(cbs[k], params);
int j =k+1;
cbs[k].setText("ITEM" + j);
cbs[k].setTextColor(Color.parseColor("#000000"));
cbs[k].setId(k+1);
cbs[k].setPadding(70, 20, 10, 10);
// check box on click listener for add in to produduct array with quntity
cbs[k].setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String chk = null;
if (((CheckBox) v).isChecked()) {
chk = Integer.toString(v.getId());
selchkboxlist.add(chk);
} else {
selchkboxlist.remove(chk);
}
}
});
}
// button on click listener code
b.setOnClickListener(new OnClickListener() {
#SuppressLint("SdCardPath")
public void onClick(View v) {
if (! selchkboxlist.isEmpty()) {
shoe erroe msg here
}else{
go ahed
}
}
});
I have exactly 20 TextView and their id is in sequence, i.e. :
R.id.textView1, R.id.textView2, R.id.textView3 ...
I have a for loop:
for (int i = 1; i < 21; i++) {
TextView textView = (TextView) findViewById(R.id.textView ...);//
textView.setText("...");
is there a way to get TextView using this for loop and set their text?
if you gave to your TextView as id R.id.textView1.. R.id.textView21, you ca use getIdentifier to retrieve the TextViews id from its name
for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
if (id != 0) {
TextView textView = (TextView) findViewById(id);
}
}
The more efficient way would be creating an array of integers and iterate through it:
int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };
for(int i=0; i < textViewIDs.length; i++) {
TextView tv = (TextView ) findViewById(textViewIDs[i]);
tv.setText("...");
}
This thread is very hold, but I faced the same sort of need : iterate through my layout structure and do something on each TextView. After having googlized it in many way, I finally decided to write my own implementation. You can find it here:
/* Iterates through the given Layout, looking for TextView
---------------------------------
Author : Philippe Bartolini (PhB-fr # GitHub)
Yes another iterator ;) I think it is very adaptable
*/
public void MyIterator(View thisView){
ViewGroup thisViewGroup = null;
boolean isTextView = false;
int childrenCount = 0;
try {
thisViewGroup = (ViewGroup) thisView;
childrenCount = thisViewGroup.getChildCount();
}
catch (Exception e){
}
if(childrenCount == 0){
try {
isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
}
catch (Exception e){
}
if(isTextView){
// do something
}
}
else {
for(int i = 0; i < childrenCount; i++){
MyIterator(thisViewGroup.getChildAt(i));
}
}
}
I have a dynamic listview with one text and one checkbox per line.when i click a button.,i need to get all checked item names & Unchecked item names separately as arraylilst.How could i do that.Examples are much better..
I used..
SparseBooleanArray checked = mainlw.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i) == true) {
Planet tag = (Planet) mainlw.getItemAtPosition(checked.keyAt(i));
String selectedName=tag.getName();
Toast.makeText(getApplicationContext(), selectedName, Toast.LENGTH_SHORT).show();
}
}
Try this out and implement this logic according to your requirement.
int cntChoice = myList.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i) == true)
{
checked += myList.getItemAtPosition(i).toString() + "\n";
}
else if(sparseBooleanArray.get(i) == false)
{
unchecked+= myList.getItemAtPosition(i).toString() + "\n";
}
}
use CHOICE_MODE_MULTIPLE in your ListView and use getCheckedItemPositions() to get the checked ones.
So Onclick of button u can do this,From this you will get the items that are checked:-
#Override
public void onClick(View v)
{
System.out.println("check"+getListView().getCheckItemIds().length);
for (int i = 0; i < getListView().getCheckItemIds().length; i++)
{
System.out.println(getListView().getAdapter().getItem((int)getListView().getCheckItemIds()[i]).toString());
}
}