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.
Related
I have an array of buttons which contains two elements.
I'd like to create a string from the text of the buttons.
The thing i am struggling with is the if statement. Basically, it is never firing the toast. Why?
String word2 = "ok";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
Change this:
if (word == word2) {
with this:
if(word.equals(word2)) {
You can't compare String with ==
Write Better Questions (basically questions)
Compare string with .equals() not ==.
Just use if(word.equals(word2) {
Why? The first one is content comparision, but the second one i just
a reference comparision so:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
Dont ever use new String(), it was just for proof
I must write it.
Change line
for (int i = 0; i < 2; i++) {
into
for (int i = 0; i < buttons.length; i++) {
So your application will be easier to change
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");
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
}
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 am making a quiz app.I am stuck on comparing answers.I have added a dialog to show if the answer is right and it works well so does toast.but when I compare for wrong answer on each word I type I get toast wrong.what's the problem here is the code what I use to compare
boolean isCorrectAnswer() {
String player_answer = "";
//concat all letters from answer buttons in one string
for (int i = 0; i < answer_line.length; i++) {
for (int j = 0; j < answer_line[i].getChildCount(); j++) {
Button b = (Button) answer_line[i].getChildAt(j);
player_answer += b.getText().toString();
}
//compare player's answer with correct
if (player_answer.equalsIgnoreCase(correct_answer)) {
ShowToast(check_toast, "Correct", Gravity.CENTER, new Point(0, -50));
return true;
} else {
ShowToast(check_toast, "Wrong", Gravity.CENTER, new Point(0, -50));
return false;
}
}
***updated coded
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_MOVE) || (event.getAction() == MotionEvent.ACTION_DOWN)) {
if (!b.getText().toString().equals("") && letters_in_answer < correct_answer.length()) {
letters_in_answer++;
System.out.println("letters: " + letters_in_answer);
int free_pos = getFirstFreeAnswerButtonPosition();
Button a = findButtonByPos(answer_line, free_pos);
a.setText(b.getText());
hideButton(b);
link_list.set(free_pos, letter_pos);
Helper.playSound(getApplicationContext(), "click");
}
//pops during correct answer
if (isCorrectAnswer()) {
toUpperCase() + "!", Gravity.CENTER, new Point(0, -50));
Helper.playSound(getApplicationContext(), "correct");
//if not all images was shown we show next image
if (cur_image < images.length - 1) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Android custom dialog example!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
generateNewLevel();
}
else {
finish();
Intent endgame = new Intent(GameActivity.this, EndActivity.class);
startActivity(endgame);
finish();
}
}
}
return false;
}
});
}
}
}
}
#user3215214 If user must type in all the letters than you could, in isCorrectAnswer() method try:
boolean isCorrectAnswer() {
String player_answer = "";
//concat all letters from answer buttons in one string
for (int i = 0; i < answer_line.length; i++) {
for (int j = 0; j < answer_line[i].getChildCount(); j++) {
Button b = (Button) answer_line[i].getChildAt(j);
player_answer += b.getText().toString();
}
//compare player's answer with correct
if(player_answer.length()==correct_answer.length()){
if (player_answer.equalsIgnoreCase(correct_answer)) {
ShowToast(check_toast, "Correct", Gravity.CENTER, new Point(0, -50));
return true;
} else {
ShowToast(check_toast, "Wrong", Gravity.CENTER, new Point(0, -50));
return false;
}
} else return false;
}