Radio button is not displaying right value - android

In my coding m having three buttons. i am getting the selected button is id and used it for comparison. But it first automatically displays the default selected button's id before clicking the button.
rdgp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
counter++;
if (counter > 5 || counter >= anarray.size()) {
Toast.makeText(testActivity.this, "" + score, 2000).show();
Intent intent = new Intent(testActivity.this, Badge.class);
intent.putExtra("Score", score);
startActivity(intent);
return;
}
rb1.setText(anarray.get(counter));
rb2.setText(an1array.get(counter));
rb3.setText(an2array.get(counter));
rb4.setText(an3array.get(counter));
rb5.setText(an4array.get(counter));
int ans = 0;
if (checkedId == R.id.radio0) {
ans = 1;
} else if (checkedId == R.id.radio1) {
ans = 2;
} else if (checkedId == R.id.radio2) {
ans = 3;
} else if (checkedId == R.id.radio3) {
ans = 4;
}
Toast.makeText(testActivity.this, "" + ans, 2000).show();
if (ans == anarray.get(counter))
;
{
score = score + 1;
}
}
});

to get the id of checked radiobutton use group.getCheckedRadioButtonId().Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.

Add the following line, in your XML for all radio buttons.
android:checked="false"

If you are getting default value from radio buttons then check in our layout file weather you used android:checked = "true".If this is the state then change it to false.

Related

Calling on click listener multiple times for updating text views?

In my activity i am showing user a question and 3 options to choose from, these options are text-views.
On clicking the text-view On click listener is performed which updates the text-views according to the option selected.
Now user again after reading the question performs on click listener on options. But this is working only twice then it stops clicking and updating.
Debug is not working either i am beginner so i am confused.
#Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.optionA) {
Answer = optionA;
LogAnswer = "a : " + optionA;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionB) {
Answer = optionB;
LogAnswer = "b : " + optionB;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionC) {
Answer = optionC;
LogAnswer = "c : " + optionC;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
}
conditions method change text-views according to option.
public void conditions(int i){
if(Answer.equals(optionA) && i == 1 )
{
questionnumber = 2;
MartialStatus = Single;
GetQuestion(2);
}
else if(Answer.equals(optionB) && i == 1 )
{
questionnumber = 2;
GetQuestion(2);
}
}
It may be that my text-view onclicklistener is calling same text-view listener which breaks.

Radio Button auto deselect after selection

I have four radio buttons in a radio group in my MCQ app. When I select a radio button and go to next question, there is a problem if I select same radio button as previous, the radio button automatically deselect, but after selecting any other button, it is working.
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
private void selectedRadioButton(int ansSelected){
if(ansSelected == 1){
optionOne.setChecked(true);
}
if(ansSelected == 2){
optionTwo.setChecked(true);
}
if(ansSelected == 3){
optionThree.setChecked(true);
}
if(ansSelected == 4){
optionFour.setChecked(true);
}
}
private void uncheckedRadioButton(){
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
optionFour.setChecked(false);
}
private void showQuestions(){
if(currentQuizQuestion >= quizCount){
currentQuizQuestion=currentQuizQuestion-1;
Toast.makeText(ShowSingleQuestionsOnline.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
else {
uncheckedRadioButton();
quizQuestion.setText(1+ currentQuizQuestion + " : " + MyQuestArrList.get(currentQuizQuestion).get("QuestName"));
int dd=Integer.parseInt(MyQuestArrList.get(currentQuizQuestion).get("QueType"),10);
optionOne.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption1"));
optionTwo.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption2"));
optionThree.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption3"));
optionFour.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption4"));
}
}
Thanks in advance.
This behavior is normal because the radio option state is not reset.
Take a look on your getSelectedAnswer() method :
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
When you go to the next question, the selected radio option state remain and when you click again on it, it value change (deselect).
To avoid this, you need to reset your radio options before go to the next question.

Data is not getting added in arraylist for radiogroup?

I want to add data in ArrayList "arr" according to the checkedId of the radio group.I have 4 radio buttons "a0,a1,a2,a3". So if I chose a1,the array list should add the value of rb2. And after selecting a1 if I select a2 then the previous value in "arr" should get updated (not get added after the first one) and so on.Any help..
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i <= mcq.size(); i++) {
switch (checkedId) {
case R.id.a0:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb1.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a1:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb2.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a2:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb3.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.a3:
// do operations specific to this selection
Toast.makeText(getApplication(),
rb4.getText(), Toast.LENGTH_SHORT).show();
break;
}
arr.add(String.valueOf(checkedId));
Log.e("", String.valueOf(arr));
}
}
});
You can use https://developer.android.com/reference/android/util/SparseArray.html
SparaseArray<Boolean> array = new SparseArray();
array.put(checkedId, rb.isChecked());
Then you can get all the checked elements of the array like this:
for(int i = 0; i< sparseArray.size(); i++) {
int id = sparseArray.keyAt(i);
Boolean isChecked = sparseArray.get(id);
if(isChecked) {
log("Identifier " + id + " is checked");
}
}

Button Print Toast When Clicked without answer Given

I have this button which calls two methods. See Code; Now i have tried to add a method on my onPictureSubmit(v) method which will print a Toast message (Please Submit Answer) if someone clicked the button without submitting an answer. Problem is it keeps crushing. Any help on how i can detect someone clicked the button without submitting answer will be appreciated.
My Button Code;
#Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
My Code :
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}
If I were you I'd declare the TextView, EditText, Button as a global variable, and then in your onCreate() I'd use the findViewById() to avoid NullPointerException.
Second, I'd check if the answerGiven (I guess is the answer) it's empty, so I'd create a method that returns me if it's empty or not the EditText.
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
Then at the time you call onPictureSubmit() call this method doing this :
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

Check for Empty EditText fails

I've tried everything from matching strings, to using TextUtils.isEmpty. No matter what I do, b is always true (even when edittext is purposely left blank) which allows the code to proceed to the next steps (this is a Madlib app).
If anybody can see why the code isn't properly checking for blank edittext's and displaying the Please Fill In All Fields" toast when one is blank, it would be very appreciated. Thanks. Sorry for the messy code.
public class Madlibs extends Fragment {
switch (((MainActivity) getActivity()).getStory()) {
case 0:
output.setText(Stories[0]);
title = Titles[0];
actionBar.setTitle(title);
editTextNumber = 12;
addEdit = new BootstrapEditText[editTextNumber];
for (int i = 0; i < addEdit.length; i++) {
addEdit[i] = new BootstrapEditText(getActivity());
l_layout.addView(addEdit[i]);
params.setMargins(0, 20, 0, 20);
addEdit[i].setLayoutParams(params);
addEdit[i].setId(i);
}
addEdit[0].setHint("Name of Sickness");
addEdit[1].setHint("Adjective");
addEdit[2].setHint("Name of Boy");
addEdit[3].setHint("Body Part");
addEdit[4].setHint("Color");
addEdit[5].setHint("Animal");
addEdit[6].setHint("Article of Clothing");
addEdit[7].setHint("Relative");
addEdit[8].setHint("Adjective");
addEdit[9].setHint("Article of Clothing");
addEdit[10].setHint("Body Part");
addEdit[11].setHint("Number");
break;
case 1:
// fragment = new Madlibs();
break;
case 2:
// fragment = new MadlibsSaved();
}
convert = (BootstrapButton) view.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i;
String s;
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else
{
b = true;
}
}
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
}
});
Your problem is here
if (b = true) { // HERE
gather();
postIt();
outputText = output.getText().toString();
}
You are using b = true which sets b to true, and since you are able to do this successfully, the conditional evaluates to true every time. What you want instead is the comparison operator ==
if (b == true) {
gather();
postIt();
outputText = output.getText().toString();
}
or even better, since the variable you are comparing is a boolean, you could just use
if (b) {} //This is "if b is true..."
if (!b) {} //This is "if b is false..."
You can see another one of my answers about this here.
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else {
b = true;
}
}
For Loop ends here and the following is outside the For Loop :
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
Problem 1 :
if(b == true) {
}
Problem 2 :
Now, suppose edittext 1 is empty, b is set to true but then it'll straightaway move ahead in the loop to edittext 2 to the last edittext which are not empty hence it'll set b to false again. You'll need to put the check inside the for loop.

Categories

Resources