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();
}
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'm trying to follow the tutorial from Firebase to allow users to login using their phone number. I've watched a tutorial video. All my code looks correct, but when I try it on my test device I receive a null pointer error.
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(Unknown Source)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.CheckPhoneNumber(PhoneLogin.java:92)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin.access$000(PhoneLogin.java:29)
at studios.p9p.chatomatic.chat_o_matic.PhoneLogin$1.onClick(PhoneLogin.java:52)
My code for the phone login is as follows:
private EditText et_check_phone_number;
private EditText et_verify_code;
private Button btn_phone;
private Button btn_verify;
private String getPhoneNumber, getVerifactionCode;
private String mVerificationId = "";
private FirebaseAuth mAuth;
private FirebaseDatabase db;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallBacks;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private ProgressDialog mloading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
mAuth = FirebaseAuth.getInstance();
initVariables();
btn_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPhoneNumber();
}
});
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPhoneNumber();
}
});
}
private void initVariables() {
et_check_phone_number = findViewById(R.id.et_phonenumber);
et_verify_code = findViewById(R.id.etvarifaction);
btn_phone = findViewById(R.id.btn_phone_login);
btn_verify = findViewById(R.id.btn_phone_verify);
mloading = new ProgressDialog(this);
}
private void CheckPhoneNumber() {
getPhoneNumber = et_check_phone_number.getText().toString();
if (TextUtils.isEmpty(getPhoneNumber))
{
Toast.makeText(this, "Phone Number Field Cant Be Empty...", Toast.LENGTH_SHORT).show();
} else{
mloading.setTitle("Checking Your Phone Number");
mloading.setMessage("It Gonna Take A Second...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
getPhoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mcallBacks);
}
}
mcallBacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneLogin.this, "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.VISIBLE);
et_check_phone_number.setVisibility(View.VISIBLE);
et_verify_code.setVisibility(View.INVISIBLE);
btn_verify.setVisibility(View.INVISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
Toast.makeText(PhoneLogin.this, "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
btn_phone.setVisibility(View.INVISIBLE);
et_check_phone_number.setVisibility(View.INVISIBLE);
et_verify_code.setVisibility(View.VISIBLE);
btn_verify.setVisibility(View.VISIBLE);
}
};
}
private void VerifyPhoneNumber() {
getVerifactionCode = et_verify_code.getText().toString();
if (TextUtils.isEmpty(getVerifactionCode)){
Toast.makeText(this, "Please Enter The Code Sent To Your SMS...", Toast.LENGTH_SHORT).show();
}else{
mloading.setTitle("Checking Your Verification code ");
mloading.setMessage("Ill Be Back In A Jiffy...");
mloading.setCanceledOnTouchOutside(false);
mloading.setIcon(R.mipmap.ic_launcher);
mloading.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, getVerifactionCode);
signInWithPhoneAuthCredential(credential);
}
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mloading.dismiss();
Toast.makeText(PhoneLogin.this, "Login Successful...", Toast.LENGTH_SHORT).show();
Intent phoneloginIntent =new Intent (getBaseContext(),Home_Screen.class);
phoneloginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(phoneloginIntent);
finish();
} else {
String mesage = task.getException().toString();
Toast.makeText(PhoneLogin.this, "Error: " + mesage, Toast.LENGTH_SHORT).show();
}
}
});
}
The "+44" I added trying to see if I was entering the wrong phone number. I tried it by adding the +44 manually into the edit text of the app first and that gave the same error.
Edit
So I've removed the line inside the Auth provider that asked if the number was larger than 9 digits as it wasn't working. Also I ran a log to see if it capturing the phone number correctly.
Log.i("Verify_Phone_Number",getPhoneNumber);
2019-07-16 14:15:30.585 32055-32055/studios.p9p.chatomatic.chat_o_matic I/Verify_Phone_Number: +447******100 and it returns correctly
Edit 2
So on further testing if I click btn_phone before entering the phone number it works correctly, but if I simply add the phone number to the edit test first then press thebtn_phone it crashes with the above message in logcat.
As per Firebase Docs you have to pass the Number with Country Code :
E.g.
phone number = +919090909090
See Following Picture :
As you can see even testing number needs country code with them.
When your app crashes it means Firebase PhoneAuthProvider.getInstance().verifyPhoneNumber() not getting the number with country code.
You can try this following code before passing to if condition :
if (et_check_phone_number.getText().toString().startsWith("+44"){
getPhoneNumber = et_check_phone_number.getText().toString();
}else{
getPhoneNumber = "+44"+et_check_phone_number.getText().toString();
}
Above Code will check whether user put prefix of your country code or not.
Ok so the way i solved this problem was to move the mcallbacks to the on create section of code. as shown below
setContentView(R.layout.activity_phone__login);
mAuth = FirebaseAuth.getInstance();
InitVariables();
AddPhoneNumberButtons();
mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getBaseContext(), "Wrong Or Invalid Phone Number...", Toast.LENGTH_SHORT).show();
AddPhoneNumberButtons();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getBaseContext(), "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getBaseContext(), "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
verificationid = verificationId;
mresendtoken = token;
Toast.makeText(getBaseContext(), "Code Sent Please Check Your SMS...", Toast.LENGTH_SHORT).show();
AddVerifyButtons();
}
};
I am working on recommendation application I using firebase to store information about user.I have used checkboxes for health status information.
I want to save all the checkbox values I selected.but in my code if I check more then one checkbox it always save the last checkbox.
This is my code How can I fix it to store all checked values?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Toolbar toolbar =findViewById(R.id.toolbarotherpages);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
databaseUser = FirebaseDatabase.getInstance("https://bonappetit-808c5.firebaseio.com").getReference("users");
users = new ArrayList<>();
addusername= findViewById(R.id.editTextname);
addphone=findViewById(R.id.editTextphone2);
mFirstCheckBox=findViewById(R.id.cbox1);
mSecondCheckBox=findViewById(R.id.cbox2);
mThirdCheckBox=findViewById(R.id.cbox3);
addhealthstatus=findViewById(R.id.editTexthealthstatus);
btnsignup =findViewById(R.id.buttonsignup2);
btnsignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signup dosignup = new Signup(); // this is the Asynctask
dosignup.execute("");
}
});
}
protected void onStart() {
super.onStart();
//attaching value event listener
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
users.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
users user = postSnapshot.getValue(users.class);
//adding artist to the list
users.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class Signup extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String username = addusername.getText().toString();
String phone = addphone.getText().toString();
String healthstatus = addhealthstatus.getText().toString();
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("") || phone.trim().equals("")) {
z += "Please fill in all fields";
} else {
int count = 0;
for (users user2 : users) {
if (user2.getPhonenumber().equals(phone)) {
count = 1;
}
}
if (count == 0) {
try {
if(mFirstCheckBox.isChecked()) {
users user = new users(username, phone,"Diabetes");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mSecondCheckBox.isChecked()) {
users user = new users(username, phone, "pressure");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mThirdCheckBox.isChecked()) {
users user = new users(username, phone,
healthstatus);
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
z = "Account created";
isSuccess = true;
}
catch (Exception ex) {
z = "Mobile number was used";
isSuccess = false;
}
}
}
return z;
}
}
To get the selected checked values you can use Switch case following code
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkBox1:
....
break;
case R.id.checkBox2:
......
break;
case R.id.checkBox3:
......
break;`
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
}
}
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