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
}
}
Related
.setNegativeButton("Favorite", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
fav=true;
user = db.userDao().findByName(email);
if(user.getmFavorite()==null)
{
// Log.i("Check List", user.getmFavorite());
Log.i("Number1", "Numer1");
//String favorite = user.getmFavorite();
user.setmFavorite(newFav);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List", user.getmFavorite());
db.userDao().Update(user);
}
else{
String favorites = user.getmFavorite();
tokenize(favorites);
Set<String> set = new HashSet<String>(items);
if(set.contains(newFav))
{
Log.i("Number221", "Numer221");
Log.i("Check List", user.getmFavorite());
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "This user is already favorite", Toast.LENGTH_SHORT);
toast.show();
}
else {
Log.i("Number331", "Numer331");
Log.i("Check List", user.getmFavorite());
String fav2 = favorites + "," + newFav;
user.setmFavorite(fav2);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List2", user.getmFavorite());
db.userDao().Update(user);
}
}
}
})
Hello I want to change the color of Button when I click the Negative button.
So if Negative Button was red , and I click it it should change to Blue, and If I click Positive Button change Negative Button's color to red. I dont know how to do this ....
You can try this -
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if(clicked)
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.YOUR_COLOR_NAME));
}
});
If I got it straight, you simply want to change the button's colour from red to blue and vice-versa each time someone presses the button. You were kind of ambiguous in the objective.
The easiest way I know of doing that is using a flag to see which colour is supposed to be on the button. You also have the setBackgroundColor method that programmatically changes the color.
So I would do something like
if(!isRed)
btn.setBackgroundColor(getResources().getColor(R.color.red));
else
btn.setBackgroundColor(getResources().getColor(R.color.blue));
being that red and blue are custom colours. You can make them in your colors.xml file.
You need to have the setBackground method inside onClick to make sure it's triggered.
try this:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View alertDialog= View.inflate(this.getActivity(), R.layout.alert_dialog,
null);
builder.setTitle(getLocalizedString("Message"))
.setView(eventEditDialogView)
.setPositiveButton(getLocalizedString("Ok"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(getLocalizedString("Cancel"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
return builder.create();
}
#Override
public void onStart() {
super.onStart();
Button positive = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
positive.setTextColor(Color.BLACK);
positive.setBackgroundColor(getResources().getColor(R.color.GrayBGColor));
}
it helps you
i have created a Form in my app. There is 3 things Mobile , Amount and Radio Button with 2 values (Male and Female) . when i press the submit Button Mobile and Amount save to Database But RadioButton values doesn't save .But when i double press on the Radiobutton its save the vale . I want the it will save when submit button is pressed.
Here is the code :
private void Submit() {
String Mobile = mobile.getText().toString().trim();
String Amount = amount.getText().toString().trim();
if (TextUtils.isEmpty(Mobile)) {
Toast.makeText(this, "Please enter Mobile", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(Amount)) {
Toast.makeText(this, "Please enter Amount", Toast.LENGTH_LONG).show();
return;
}
demoRef.push().child("Mobile").setValue(Mobile);
demoRef.push().child("Amount").setValue(Amount);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
switch (i){
case R.id.male:
demoRef.push().child("Method").setValue("Male");
break;
case R.id.female:
demoRef.push().child("Method").setValue("Female");
break;
}
}
});
You can do it like below. I am adding a sample code.
1.create a variable to store gender value which you will get from radio button and then set the listener to radioGroup in onCreate().
2. Modify the Submit() method as shown below.
public class MainActivity extends AppCompatActivity {
// add this variable to hold gender value.
private String gender = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your all other code which is already inside onCreate();
....
// [EDIT BEGIN]
RadioButton genderBtn=(RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
gender = genderBtn.getText().toString();
// [EDIT END]
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
switch (i){
case R.id.male:
gender = "Male";
break;
case R.id.female:
gender = "Female";
break;
}
}
});
}
// Modify submit method like below.
private void Submit() {
String Mobile = mobile.getText().toString().trim();
String Amount = amount.getText().toString().trim();
if (TextUtils.isEmpty(Mobile)) {
Toast.makeText(this, "Please enter Mobile", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(Amount)) {
Toast.makeText(this, "Please enter Amount", Toast.LENGTH_LONG).show();
return;
}
demoRef.push().child("Mobile").setValue(Mobile);
demoRef.push().child("Amount").setValue(Amount);
demoRef.push().child("Method").setValue(gender);
}
you can do this
private void Submit() {
String Mobile = mobile.getText().toString().trim();
String Amount = amount.getText().toString().trim();
if (TextUtils.isEmpty(Mobile)) {
Toast.makeText(this, "Please enter Mobile", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(Amount)) {
Toast.makeText(this, "Please enter Amount", Toast.LENGTH_LONG).show();
return;
}
demoRef.push().child("Mobile").setValue(Mobile);
demoRef.push().child("Amount").setValue(Amount);
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.male:
demoRef.push().child("Method").setValue("Male");
break;
case R.id.female:
demoRef.push().child("Method").setValue("Female");
break;
}
}
Use this code while submit
public void onClick(View arg0) {
int selected=radioGroup.getCheckedRadioButtonId();
RadioButton genderBtn=(RadioButton) findViewById(selected);
String gender = genderBtn.getText().toString();
}
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
So I have some code that sets an onClickListener for a button that doesn't seem to work on devices with screen sizes less than 4 inches, but only for specific buttons. I'm not sure why, because it doesn't seem to be an effect OS Level version, but only screen size.
I have logging code in the onclick method that shows all the buttons registering and firing correctly except the new_game button. Any input on why this might be happening would be appreciated.
Code from OnCreate:
Button acknowledgements = (Button) findViewById(R.id.acknolwedgments_word_Game);
acknowledgements.setOnClickListener(this);
Button quit = (Button) findViewById(R.id.quit_word_game_button);
quit.setOnClickListener(this);
Button new_game = (Button) findViewById(R.id.word_game_new_Button);
Log.e("NEW GAME BUTTON", String.valueOf(new_game));
new_game.setOnClickListener(this);
Log.e("SET ONCLICK", "DONE");
OnClickListener:
public void onClick(View view) {
int id = view.getId();
Log.e("CLICKED BUTTON", String.valueOf(view));
if (id == R.id.quit_word_game_button){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
else if (id == R.id.acknolwedgments_word_Game){
Intent i = new Intent(this, Acknowledgements.class);
startActivity(i);
}
else if (id == R.id.word_game_new_Button){
final AlertDialog alert = new AlertDialog.Builder(word_game_mainscreen.this).create();
final EditText edit = new EditText(getBaseContext());
edit.setHint("Username");
alert.setView(edit);
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alert.dismiss();
}
});
alert.setButton(DialogInterface.BUTTON_POSITIVE, "PLAY!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String opponent = String.valueOf(edit.getText());
new AsyncTask(){
#Override
protected Object doInBackground(Object[] objects) {
//Code to synchronize it to a server
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Log.e("POST EXECUTE", (String)o);
//Creates intent to take you to the game
}
}.execute();
}
});
alert.show();
}
else if (id == R.id.togglesound){
ToggleButton music = (ToggleButton) findViewById(R.id.togglesound);
if (music.isChecked()){
Music.play(this, R.raw.wordgame);
}
else{
Music.stop(this);
}
}
}
Simple suggestion: swith case is far better than if-else and class_name.this is mostly friendly than getBaseContext().
For showing AlertDialog we have to first create the builder.Something like:
AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(...).setTitle(...)
.setView(...)
.setPositiviButton(...)
.setNegativeButton(...);
//Now create the builder and assign to AlertDialog
dialog = builder.create();
dialog.show;
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