0
votes

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: enter image description here

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.

2

2 Answers

0
votes

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.

0
votes

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.