So I'm trying to learn Kotlin and have been using Android Studios to practice and learn. Currently I'm trying to make a simple activity with RadioGroup (with Radio Buttons), save the selected value, and then display how much of each value (radiobutton) was selected.
My question is, how do I print which button was selected, and how many of this type of button was selected?
I tried the following:
//in MainActivity.kt in my MainActivity class
s1RadioGroup.setOnCheckedChangeListener { _, checkedId ->
//if catButton was selected add 1 to variable cat
if(checkedId == R.id.catRadio) {
catSum += 1
print(catSum)
}
//if dogButton was selected add 1 to variable dog
if(checkedID == R.id.dogRadio) {
dogSum += 1
print(dogSum)
}
Not sure if I'm going about it the right way, but the desired output is:
I have layout, ID's, clear button, and everything else working. But I'm not sure how to use onClickListener event on 'SaveButton' to save selected radio button and then displaying results (Ex: Cat = 1, Dog =2). I would appreciate any suggestions, or if you can point me in the right direction.
You can maybe try something like this:
RadioButton rb = (RadioButton) findViewById(R.id.radio_button);
// restore previous state
rb.setChecked(lastButtonState);
// set a listener
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call this to enable editing of the shared preferences file
// in the event of a change
SharedPreferences.Editor editor = sharedpreferences.edit();
Boolean isChecked = rb.isChecked();
// use this to add the new state
editor.putBoolean(BUTTON_STATE, isChecked);
// save
editor.apply();
}
});
I realize that this is in Java, and you're asking for kotlin, but a SharedPreference, is what you would need to save the radio button's state.
if you want to save all datam you can use database or sharedprefrence.
and if you only want just display value is clicked, you can make like this in button save.
String result1 = ""
String result2 = ""
String result3 = ""
RadioGroup radioGroup = findViewById('yourRGidFromXml')
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton rb = findViewById(selecetedId)
result1= rb.getText.toString()
Log.i("ID", String.valueOf(selectedId));
}
});
//this just for see result
btnSave.OnclikListener(view -> {
Log.i("Result1",result1)
})
you can copy code and android will convert that code to kotlin.
Related
I need to pass the value selected in a RadioGroup on one Activity to a series of 5 CheckBoxs in another.
I don't know enough about Global Variables to be able to just do this myself
So I have 5 RadioButtons in a RadioGroup in my XML, like this:
<RadioButton
android:id="#+id/rdoInternet1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dedicated and Resilient"
android:layout_weight="1"/>
And then in my Java I was going to a series of Nested if statements
//find the id of the RadioGroup and store it in a variable
RadioGroup question1RadioGroup = (RadioGroup) findViewById(R.id.radioInternet);
question1RadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//set a listener on the RadioGroup
#Override
public void onCheckedChanged(RadioGroup view, #IdRes int checkedId) {
//checkedId refers to the selected RadioButton
//Perform an action based on the option chosen
if (checkedId == R.id.rdoInternet1) {
/*Nested if statement setting value 1 */
} else {
if (checkedId == R.id.rdoInternet2) {
/*Nested if statement setting value 1 */
} else {
if (checkedId == R.id.rdoInternet3) {
/*Nested if statement setting value 1 */
} else {
if (checkedId == R.id.rdoInternet4) {
/*Nested if statement setting value 1 */
} else {
if (checkedId == R.id.rdoInternet5) {
/*Nested if statement setting value 1 */
But then I don't know how to store it as a global variable and then would have recalled this in the next screen using nested ifs again to say which checkbox to Check.
So what I need to know is, is there a better way to do this and how to store up the Global Value
all you have to do is adding boolean variables as intent extra :
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("yourBoolName", true);
and then get it in your next activity :
Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
I want to highlight right and wrong option when user clicks a button after checking an radio button. If that option is right, highlight. Else highlight right option.
Is there any way to get radio button id in a group based on its value? Or Do I need to use switch case?
I searched enough but not able to find out what I need.
Edit
I have simple layout which contains one question, 4 choices, one button. User check a radio button and click the check button. If user selects wrong option, highlight the correct option. I know what is correct option by value.
choice1, choice2, choice3, choice4 are four radio buttons. User checks choice3. But choice2 is correct. How do I select choice2 by value in this radio group.
group.getRadioButtonId("choice2")
Anything similar to this?
You could iterate through the children of your RadioGroup to get the required one:
int count = radioGroup.getChildCount();
for (int i = 0 ; i < count; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.getText().equals("choice2")) {
int id = button.getId(); // the ID you're looking for
}
}
You Can check like this
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int rbId = group.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
switch (group.getId()) {
case R.id.radiogroupID:
if (rb.getText().toString().equalsIgnoreCase("right")) {
// your logic
} else {
//your logic
}
}
}
you can use these line. its working for me
int checkedId = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(checkedId);
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
First check which option is true. hear choice 2 OK. set by default is checked true and than check user checked value . if user select other option than display message and pass true option we already checked true
Create an int array with all the ids of the radiobutton
int[] rb_IDs=new int[]{R.id.rb1,R.id.rb2,R.id.rb3};
Then inside your button click :
RadioGroup rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i=0;i<rb_IDs.length;i++)
{
RadioButton rb=(RadioButton)findViewById(rb_IDs[i]);
if (rb.getText().toString().equals("YOUR CORRECT ANSWER")&&!rb.isChecked())
{
//
//Do your thing
//
//ID of the correct answer Radiobutton is
int id=rb_IDs[i];
//HighLighting the answer
rb.setBackgroundColor(Color.parseColor("#00ff00"));
break;
}
}
}
});
I am making an application that has list and Radio Buttons. My Layout contains of the following : a list , A button .
The List contains of Radio buttons. Two radio Buttons. After checking the buttons. I want to make a loop that reads the values of how many are in Button one and how many in Button Two.
This is how I have done so far.
ListViewStudentEditAbsence country ;
for(int i=0;i<listViewStudentNames.size();i++) {
country = listViewStudentNames.get(i);
if (country.getAbsence()==1) {
Absence[i] = "1";
} else {
Absence[i] ="0";
}
}
But It doesn't seem to work.
In your CustomAdapter getView() method
int value=0; //globally
RadioGroup radioGroup = (RadioGroup) convertView.findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
if (checkedId == R.id.rbutton1) {
value=10; //a's value
} else if (checkedId == R.id.rbutton2) {
value=20; //b's value
}
}
});
https://stackoverflow.com/questions/11194515/android-get-value-of-the-selected-radio-button
Android getting value from selected radiobutton
Hope it works. This two links give you proper knowledge about fetching value.
I need help from any one..
I'm facing difficult in checks the radio button.
My concept is how to save the radio button in arraylist and again how to check the selected value from arraylist. If suppose imagine a quiz app. I have a set of questions and answers in a separate array. I'm displaying it.Its fine. Now if i came to pervious question i should check the selected answer already which has stored in an arraylist. Likewise for next question. How to implement this? I feel difficult in this.
When 1st question displays i check and get the answer like this..
btn_practicerg.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)group. findViewById(checkedId);
String temp = radioButton.getText().toString();
When i press next button for next question like do like this same and get the answer in a string and while i press previous i have used same like that.. but i should not do like that instead i should check already choosen answer..
Sorry for my bad english. Thanks a lot in Advance..
radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub for(int i=0; i
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
String text;
if (btn.isPressed() && btn.isChecked() && questNo < 5)
{
Log.e("corrAns[questNo]",corrAns[questNo]);
if (corrAns[questNo].equals(btn.getText()) && flag==true)
{
score++;
flag=false;
checked = true;
}
else if(checked==true)
{
score--;
flag=true;
checked = false;
}
}
} tvScore.setText("Score: " + Integer.toString(score) + "/5"); Log.e("Score:", Integer.toString(score)); } });
this is the snippet you can go ahead and modify according to your need...
i hope this will help
also check this link
I don't know about your implementation, but I would have a class called Question, for example, that would contain the question, the answers in an array, the right answer (just the id of the array) and the selected answer (just the id of the array).
So, in your program you will have a set of Question objects and you will have the option selected and then you can just put radioButton.toggle();
Use HashMap<RadioGroup,Integer> hashMap to store the value inside the
btn_practicerg.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)group. findViewById(checkedId);
String temp = radioButton.getText().toString();
hashMap.put(group,checkedId);
later you can retrieve the value of RadioGroup in hashmap just pass the object of RadioGroup to the HashMap as key. eg
RadioGroup mOption = (RadioGroup) findViewById(R.id.option);
mOption.check(hashMap.get(mOpiton));
i have a radio group with two radio buttons in it. I want to get the value of the radio button and then store it in the database..how do i do that?? Pls help! I searched for it but all in vain!
I tried this code but my activity stops working after using it
rg=(RadioGroup)findViewById(R.id.radioGroup2);
if(rg.getCheckedRadioButtonId()!=-1)
{
int id=rg.getCheckedRadioButtonId();
View radioButton=rg.findViewById(id);
int radioid=rg.indexOfChild(radioButton);
RadioButton btn = (RadioButton) rg.getChildAt(radioid);
Father_spouse=(String)btn.getText();
}
if you want to store the text label of your RadioButton then use this :
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
if(selectedId != -1) {
// find the radiobutton by returned id
selectedRadioButton = (RadioButton) findViewById(selectedId);
// do what you want with radioButtonText (save it to database in your case)
String radioButtonText = selectedRadioButton.getText();
}
if you want to save a boolean value so test on the selectedId of your RadioButtons and save a 0 or 1 to your database column (Example of two radio buttons to enable/disable updates) :
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
boolean isAllowUpdate = false;
switch(selectedId) {
case R.id.radioAllowUpdate : isAllowUpdate = true; break;
case R.id.radioDisableUpdate : isAllowUpdate = false; break;
}
//save it to database
if(isAllowUpdate)
// true ==> save 1 value
else
// false ==> save 0 value
EDIT :
if you should control the selected value and when send it to database, see this tutorial