Question: I am trying to take the index of the selected radio button and use that in the onClick function.
Example:
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (getIndex(k) == 0) {
DO THIS
}
if (getIndex(k) == 1) {
DO THAT
}
});
I have the following code in my Android app:
int POS; //global variable assigned right under MainActivity
final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);
Button btnCalc = (Button) findViewById(R.id.btnCalculate);
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, Integer.toString(getIndex(POS1)), Toast.LENGTH_SHORT).show(); //DOESN'T WORK
});
rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Method 1
int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
getIndex(pos);
Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
}
});
public int getIndex(int POS1) {
Toast.makeText(MainActivity.this, Integer.toString(POS1), Toast.LENGTH_SHORT).show(); // WORKS
return POS1;
}
How can I achieve this line:
Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();
To call the function to get the value of k?
Assuming your question is in the Toast such that it is: "CALL FUNCTION GETINDEX() to get value"
Toast.makeText(MainActivity.this, Integer.toString(getIndex(int)), Toast.LENGTH_SHORT).show();
You pass in the integer that is returned though so you could just go with the following (under my assumptions of your code):
Toast.makeText(MainActivity.this, Integer.toString(int), Toast.LENGTH_S
Related
This is the method I have created to check the condition
For the right answer, I am showing the png image and the same for the wrong answer
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
I have called the method checkAnswer() method in the true button click and false button click below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(true);
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(false);
mFalseButton.setEnabled(false);
mTrueButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
Now, i have used intent method in Score Button click and in the ScoreActivity.class i want to show the
store in textview.
please tell me how to count the true answer and wrong answer and store the score in the variable which i
can show in textview
Please help me.
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
finish();
}
});
private int trueCount = 0;
private int falseCount = 0;
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
trueCount++;
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
falseCount++;
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
...
//Displaying int textView
textView.setText(String.format("Right count: %d False count: %d", rightCount, falseCount));
mFinalMarks = (TextView)findViewById(R.id.final_marks);
mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks out of 10 ");
getIntent().getStringExtra("PLUS_MARKS");
// it is showing null instead of score
I have been recently having an error when compiling my android code onto an emulator. The game is that when you click a button, it gives you a math question displayed on a textView, and user types their answer (in numbers) and clicks the button 'check' When I click that button, it always returns false.
Anyone knows how to fix this?
Java Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mathQuestion = findViewById(R.id.magic_textview);
redCircle = findViewById(R.id.math_ball);
yellowbox = findViewById(R.id.yellow_box);
yellowboxY = 1550f - 130f;
yellowbox.setY(yellowboxY);
yellowboxX = 472f;
yellowbox.setX(yellowboxX);
type_answer = findViewById(R.id.type_answer);
Button checkButton = findViewById(R.id.check_button);
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(redCircleX == yellowboxX && redCircleY == yellowboxY){
mathQuestion.setText("What is "+math_int1+" + "+math_int2+" ?");
math_int1 = r.nextInt(20);
math_int2 = r.nextInt(20)+1;
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int2);
Button checkAnswer = findViewById(R.id.check_answer);
checkAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Error? Always returning false?
if (type_answer.getText().toString().contains (Integer.toString( math_int1 + math_int2))) {
Toast t = Toast.makeText(GameActivity.this, "Success!", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t2= Toast.makeText(GameActivity.this, type_answer.getText().toString(), Toast.LENGTH_SHORT);
t2.show();
}
}
});
}else{
Toast.makeText(GameActivity.this, "Incorrect Or Error", Toast.LENGTH_SHORT).show();
}
}
});
Button upButton = findViewById(R.id.up_button);
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveUp();
}
});
Button downButton = findViewById(R.id.down_button);
downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveDown();
}
});
Button leftButton = findViewById(R.id.left_button);
leftButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveLeft();
}
});
Button rightButton = findViewById(R.id.right_button);
rightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveRight();
}
});
Button resetCircleXY = findViewById(R.id.reset_button);
resetCircleXY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initCircleXY();
Toast.makeText(GameActivity.this, "Reset Ball's Position", Toast.LENGTH_SHORT).show();
}
});
upButton.performClick();
leftButton.performClick();
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
private void moveUp(){
redCircleY -= ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveDown(){
redCircleY += ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveLeft(){
redCircleX += ballMoveDis;
redCircle.setX(redCircleX);
}
private void moveRight(){
redCircleX -= ballMoveDis;
redCircle.setX(redCircleX);
}
private void initCircleXY(){
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
}
Help is greatly appreciated, Thanks
First mistake
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int1); // this should be math_int2
BUT consider adding two strings
string_math_int1 + string_math_int2)
"10" + "20"
equals
"1020" not "30"
Maybe
if (type_answer.getText().toString().equals(String.valueOf (math_int1 + math_int2) {
Answer to newly formatted question:
Your issue has to do with comparing two strings when you want to check their int values. You could try using Integer.parseInt() on your EditText's entry. Just be aware you will need to do a try on it to catch an exception in the case of your EditText having any non numeric characters.
Answer to previous question about crash before edit:
Your crash isn't with your EditText. It is this line:
Toast.makeText(GameActivity.this,math_int1 + math_int2 , Toast.LENGTH_SHORT).show();
By passing it an int value, it is attempting to look up a string with that id. If your intent is to display the sum of those ints, it should look something like:
Toast.makeText(GameActivity.this, String.valueOf(math_int1 + math_int2), Toast.LENGTH_SHORT).show();
I have a basic program. I wish to set the background of individual buttons, based on user click count, then IF all buttons have the same background, the user will proceed to the next activity. Simple enough, or so I thought... I just can't seem to figure out how to compare the IF statements to each-other. I've spent like an hour writing and rewriting code, trying to find an answer. There has to be an easy answer I'm missing and just can't wrap my mind around.
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
Button a1;
Button a2;
Button a3;
Button a4;
static int count1=0;
static int count2=0;
static int count3=0;
static int count4=0;
public void addListenerOnButton() {
final Button a1 = (Button) findViewById(R.id.a1);
a1.setOnClickListener(new OnClickListener()
#Override
public void onClick(View v) {
count1=count1+1;
if(count1==1||count1==4||count1==8)
{ a1.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked !", Toast.LENGTH_LONG).show();}
else if(count1==2||count1==6)
{a1.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +count1, Toast.LENGTH_LONG).show();}
else{a1.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +count1, Toast.LENGTH_LONG).show();
}}});
final Button a2 = (Button) findViewById(R.id.a2);
a2.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==2||clickcount==4||clickcount==7)
{ a2.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==1||clickcount==3)
{a2.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a2.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
final Button a3 = (Button) findViewById(R.id.a3);
a3.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1||clickcount==2||clickcount==6)
{ a3.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==4||clickcount==5||clickcount==7)
{a3.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a3.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
final Button a4 = (Button) findViewById(R.id.a4);
a4.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==3||clickcount==5||clickcount==7||clickcount==8)
{ a4.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==2||clickcount==9)
{a4.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a4.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
}
}
public void checkFunc(){
if(count1==1)
{
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/"));
startActivity(browserIntent);
}
}
}
One way I have considered achieving my goal is something along the lines of
if((a1.setBackgroundColor(Color.BLUE)==true)|| (a2.setBackgroundColor(Color.BLUE)==true))
Edit** So after trying a few things I edited my code a bit and still cant get it to work. Any further suggestions?
You can do the comparison using static variables instead. Also declare the variables globally. It's not a great approach, but here goes:
//global static vars
static int count1=0;
static int count2=0;
static int count3=0;
static int count4=0;
//make sure you include your conditions. I've added this just for reference
public void addListenerOnButton() {
a1.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v)
{
count1++;
}
}
a2.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v)
{
count2++;
}
}
//And so on...
}
public void checkFunc()
{
if(count1==count2==count3==count4)
{
//do something
}
}
I suggest that, declare clickCount variables inside class, not inside click handler. So you can reach each button's click count every clickHandler method. So, write a method that compares clickCount's, and call this method inside every clickHandler.
private int clickCount1, clickCount2, clickCount3, clickCount4;
private void compareClickCounts(){
// Compare clickCounts and change buttons properties
}
I have 2 activities. In the first one i choose a level. In the second i play the game.In the second activity I answer questions and everytime I answer correctly I add one value to my arraylist. When the game ends a user goes back to level select activity and there he can see his score. For example: Level1: you answered 17 questions correctly. How can I achieve that? I tried using sharedpreferences but had no luck. It always shows 0. Im guessing its because it gets the value at the start of the game, when the list is empty. How to show the values after the game has ended when the list is filled?
This is the game activity in witch I create a list, store values in it and answer questions.:
public class MainActivity extends Activity {
Button mYes;
Button mNo;
TextView mQuestion;
Button btnClosePopup;
TextView mPopupText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] count = {0}; // Global array.
final int[] score = {0};
//final int[] intArray = new int[3];
mYes = (Button) findViewById(R.id.button2);
mPopupText = (TextView)findViewById(R.id.popupTekstas);
btnClosePopup = (Button)findViewById(R.id.btn_close_popup);
mNo = (Button) findViewById(R.id.button);
mQuestion = (TextView) findViewById(R.id.textView);
//Creating questions. (Question, boolean, answer).
final Question first = new Question("Do i understand this code?", true, "Only Jesus knows");
final Question second = new Question("Why dont i understand this code?", false, "Im not Jesus");
final Question third = new Question("Why I am not Jesus?", true, "2fat.");
//Creating Lists for questions and boolean values.
final ArrayList<Question> questions = new ArrayList<Question>();
final ArrayList<Boolean> type = new ArrayList<Boolean>();
final ArrayList<Integer> points = new ArrayList<Integer>();
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("taskai", points.size());
editor.commit();
//mResult.setText("zdr");
//Adding questions to the question list
questions.add(first);
questions.add(second);
questions.add(third);
// Adding boleans to the boolean list
type.add(first.correctAnswer);
type.add(second.correctAnswer);
type.add(third.correctAnswer);
//Show the first question on Activity start.
mQuestion.setText(questions.get(0).question);
// Open PopUp Window on true button click.
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
//Show the first answer on first button click.
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
// When PopUp button closes open the next question with the if/else conditions.
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the question is true show next question/ else close app
if (type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner");
builder.setMessage("You won, play again?");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
// mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
mNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(!type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner")
.setMessage("You won, play again?")
.setCancelable(false)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
//mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Klaida!");
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
}
public PopupWindow pwindo;
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 500, 570, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
public View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
pwindo.dismiss();
}
};
In this activity I try to get the list values and show them:
public class LevelSelectActivity extends MainActivity {
Button mLevel1;
public TextView mResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_select);
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
int result = sharedPref.getInt("taskai", 0);
mLevel1 = (Button)findViewById(R.id.level1);
mResult = (TextView)findViewById(R.id.Resultas);
// mResult.setText(players.size()-1 + "/" + 3);
mResult.setText("" + result);
mLevel1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startGame = new Intent(LevelSelectActivity.this, MainActivity.class);
startActivity(startGame);
}
});
}
I don't know for sure what's happening in your code, but I do know preferences aren't the best way to pass data.
You are better off using a set results/ get results pattern.
The first activity uses
startActivityForResult(intent, LEVEL_REQUEST);
It will also create a function to read back the data after it is done. That'll look something like:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == LEVEL_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
}
}
}
The activity sending the results will do this to publish the results:
Intent resultsIntent=new Intent();
//Set data in the intent, note this intent is returned to the original function in `onActivityResult`
setResult(Activity.RESULT_OK,resultsIntent);
The second activity uses
I'm Developing an android app in which the Questionnaire activity contains Questions which as radio Buttons and also a Button(Next).So when the button is pressed I've to check whether all the Questions are answered.if any of the Question is not answered then a alert message should pop up stating that the particular Question no is not answered.Can anyone please help me with the java code.
Thanks in Advance.
Here is the Java code. I've commented on the line where I'm getting an error.
public class ManagerQuestionnaire1 extends Activity
{
RadioButton rb1;
RadioButton rb2;
RadioButton rb3;
RadioButton rb4;
RadioButton rb5;
RadioButton rb6;
RadioButton rb7;
RadioButton rb8;
RadioButton rb9;
RadioGroup rg1;
RadioGroup rg2;
RadioGroup rg3;
Button next;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manager_questionnaire1);
addButtonListener();
}
public void addButtonListener()
{
rb1=(RadioButton)findViewById(R.id.radioButton1);
rb2=(RadioButton)findViewById(R.id.radioButton2);
rb3=(RadioButton)findViewById(R.id.radioButton3);
rb4=(RadioButton)findViewById(R.id.radioButton4);
rb5=(RadioButton)findViewById(R.id.radioButton5);
rb6=(RadioButton)findViewById(R.id.radioButton6);
rb7=(RadioButton)findViewById(R.id.radioButton7);
rb8=(RadioButton)findViewById(R.id.radioButton8);
rb9=(RadioButton)findViewById(R.id.radioButton9);
rg1=(RadioGroup)findViewById(R.id.Mquestion1);
rg2=(RadioGroup)findViewById(R.id.Mquestion2);
rg3=(RadioGroup)findViewById(R.id.Mquestion3);
Button next=(Button)findViewById(R.id.button1);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(validationSuccess()){
Intent intent = new Intent(ManagerQuestionnaire1.this, ManagerQuestionnaire2.class);
startActivity(intent);
}
}
});
}
private Boolean validationSuccess()
{
if(rg1.getCheckedRadioButtonId()==-1&&rg2.getCheckedRadioButtonId()==-1&&rg3.getCheckedRadioButtonId()==-1)
{
alertDialog();
return false;
}
if(rb1.isChecked()==false&rb2.isChecked()==false&&rb3.isChecked()==false)
{
alertDialog();
return false;
}
if(rb4.isChecked()==false&&rb5.isChecked()==false&&rb6.isChecked()==false)
{
alertDialog();
return false;
}
if(rb7.isChecked()==false&&rb8.isChecked()==false&&rb9.isChecked()==false)
{
alertDialog();
return false;
}
return true;
}
private void alertDialog()
{
AlertDialog alert= new AlertDialog.Builder(ManagerQuestionnaire1.this).create();
alert.setTitle("Exception:Complete the Questions");
alert.setMessage("Please ensure all Questions are answered");
}
You may also use below code:
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validationSuccess()){
Intent intent = new Intent(ManagerQuestionnaire1.this, ManagerQuestionnaire2.class);
startActivity(intent);
}
}
});
private Boolean validationSuccess(){
if(rg1.getCheckedRadioButtonId()==-1&&rg2.getCheckedRadioButtonId()==-1&&rg3.getCheckedRadioButtonId()==-1){
alertDialog();
return false;
}
//optional to add whether to check which questn is not answered
if(mBtn1.isChecked()==false&&mBtn2.isChecked()==false&&mBtn3.isChecked()==false){
alertDialog();
return false;
}
if(mBtn4.isChecked()==false&&mBtn5.isChecked()==false&&mBtn6.isChecked()==false){
alertDialog();
return false;
}
if(mBtn7.isChecked()==false&&mBtn8.isChecked()==false&&mBtn9.isChecked()==false){
alertDialog();
return false;
}
return true;
}
private void alertDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
ManagerQuestionnaire1.this);
alertDialogBuilder.setMessage("Please ensure all Questions are answered")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
where mBtn1,mBtn2..are your radioButton's
You can get the id of the checked RadioButton in a particular RadioGroup by:
int selectedId = radioGroup.getCheckedRadioButtonId();
You can try something like below.
public void onClick(View v) {
int checked = rg1.getCheckedRadioButtonId();
switch(checked)
{
case R.id.always:
Toast.makeText(ManagerQuestionnaire1 .this, "First is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.sometime:
Toast.makeText(ManagerQuestionnaire1 .this, "Second is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.notatall:
Toast.makeText(ManagerQuestionnaire1 .this, "Third is selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(ManagerQuestionnaire1 .this, "pleas check any button", Toast.LENGTH_SHORT).show();
break;
}
}
If you want to show Alert dialog instead of toast then you can replace it with alert dialog. Like wise same for your rg2 and rg3 you can check.
you must be having multiple radiogroups on the screen.
Here is the example to check whether any all questions are attempted or not in your case
int radioGroupIds = new int []{R.id.rg1, R.id.rg2, r.id.rg3};
for(int rg : radioGroupIds)
{
int selectedAns = (RadioGroup)findViewById(rg).getCheckedRadioButtonId();
// Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
if(selectedAns == -1)
{
// TODO answer is not selected
// This represents that there is missing answer of any question
}else
{
// TODO answer is selected
// This represents that answer is selected for question
}
}