saving the state of radiobuttons - android

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages where each page has only one question and 4 answers(a,b,c,d). For this task I have defined 4 radiobuttons for each question. What I want to obtain is that if any radiobutton is checked , the other radiobuttons are unchecked (radiobuttons checked false) . And i want that when the user goes thorugh differentes pages the value can be retrieved. I have tried this code , however it worked fine with selecting one answer and uncheck the others , but it didnt work for saving the state of the radiobuttons even though i used shared preferences .
public class Page1 extends Activity {
RadioButton r1a , r1b , r1c , r1d ;
Button b1n ; // this is a next-button that will navigate to page2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SharedPreferences pref ;
r1a = (RadioButton) findViewById(R.id.Q1a);
r1b = (RadioButton) findViewById(R.id.Q1b);
r1c = (RadioButton) findViewById(R.id.Q1c);
r1d = (RadioButton) findViewById(R.id.Q1d);
b1n = (Button) findViewById(R.id.B1n);
pref = getSharedPreferences("Answers", 0);
final Editor editor = pref.edit();
r1a.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1a.isChecked()){
r1b.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1b.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1b.isChecked()){
r1a.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1c.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1c.isChecked()){
r1a.setChecked(false);
r1b.setChecked(false);
r1d.setChecked(false);
}
}
});
r1d.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1d.isChecked()){
r1c.setChecked(false);
r1a.setChecked(false);
r1b.setChecked(false);
}
}
});
// i use this to save the state , but it fails :(
editor.putBoolean("questionA", r1a.isChecked());
editor.putBoolean("questionB", r1b.isChecked());
editor.putBoolean("questionC", r1c.isChecked());
editor.putBoolean("questionD", r1d.isChecked());
editor.commit();
}
public void move12(View view) { // instantiated when b1n is clicked
Intent intent = new Intent(this , P2.class) ;
startActivity (intent) ;
}
}
i have two questions here :
is this code ok ? or is there a better idea for handling the checked buttons ?
the shared preference does not work , anytime i return to page1 all the radiobuttons are unchecked and the state fail to be saved. what is the cause of the problem ?and how can it be resolved ? any ibeads please .

Your code for saving state is ok. Your radioButtons are unchecked because nowhere in Page1 you actually read from SharedPreferences and set their state. You could add this in onCreate():
r1a.setChecked(pref.getBoolean("questionA", false));
r1b.setChecked(pref.getBoolean("questionB", false));
r1c.setChecked(pref.getBoolean("questionC", false));
r1d.setChecked(pref.getBoolean("questionD", false));
First though, check if preference file is present and if states of each buttons have been saved.

You can sort of truncate your onCheckChangedListeners to just one and then have a switch that checks to see which RadioButton was clicked, but the way you did it is fine.
As per saving the data, it doesn't look like you're attempting to read the data that you saved. First of all, you should put all of your data saving inside the move12 method. Secondly, try adding something like this to your onCreate:
bool aChecked = prefs.getBoolean("questionA",false);
if(aChecked)
r1a.setChecked(true);
Do that for all four.

Related

How can I make a switch buttons change the background of an Android Studio TextView?

I would like to know how I can change the background-color of a TextView, through a switch button. It is necessary to clarify that my switch buttons are in MainActivy and my TextView are in other Activities, to which I access like this:
tvBoton = (TextView) findViewViewById(R.id.Schedule);
tvBoton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, central.class);
startActivity(i);
}
});
I don't know if it influences anything, but my switch buttons have SharePreferences:
pol = (Switch) findViewById(R.id.switch18);
sharpol = getSharedPreferences("pol", MODE_PRIVATE);
final SharedPreferences.Editor editorpol = sharpol.edit();
pol.setChecked(sharpol.getBoolean(ex, false));
pol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean ispolChecked) {
if (ispolChecked) {
editorpol.putBoolean(ex, true);
politica=(TextView) findViewViewById(R.id.polit);
politica.setText("Not working");
} else {
editorpol.putBoolean(ex, false);
}
editorpol.commit();
}
});
As it is in the previous code, I tried inside the ispolChecked, in the true option, to reference the TetView, and then put setText, but this TextView, being inside another layout does not work. I also put setContentView(R.layout.main_activity) several times, but changing it to the respective layouts, but it didn't work either.
Honestly, I don't know what to do anymore. Thanks for your answers.
Use SharedPreference to store the state of the Switch and when you have stored it go to the next Activity and change background color of TextView based on the state of the SharePreference.

Kotlin how to save Radio Button and display values?

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.

Using the selected state of a Android Toggle button / switch

I am looking to add a toggle button or switch to my current app. What i am wanting to do is write the current clicked state to a string so that this can be called back later by another part of the app.
what i will ultimately be doing with this is using the selected item from my spinner, and then the state of my switch to combine the two and write this to a text file or Db.
So the spinner works and writes and i can save its selected state as follows.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SelectedServer = parent.getItemAtPosition(position).toString();
}
so when i go to save this later in my code i can call the SelectedServer string to save this data.
My question is how can i replicate this for a switch, where one state will be for true and save the value &true, and the other for false and save the value &false to be called later.
the reason for this is that, the saved value will be added later to the selected item from the spinner.
all help, advise appreciated
Dave
**** savesettings event
public void saveSettings(View view) {
File txtFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder/");
if (!txtFolder.exists()) {
txtFolder.mkdir();
}
File file = new File(txtFolder, "setting.txt");
String.valueOf(SelectedServer.getBytes());
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(SelectedServer.getBytes());
fos.close();
Toast.makeText(getApplicationContext(),"Setting Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So what i am looking to do is where i have
FileOutputStream fos = new FileOutputStream(file);
fos.write(SelectedServer.getBytes());
I will be adding the state of the toggle switch, so was looking at something like fos.write(SelectedServer+SelectedState.getBytes());
but that doesn't seem to work, is there a way to join these to saved strings together like this?
In the Android Developer library there is a good example of a toggle switch.
(https://developer.android.com/guide/topics/ui/controls/togglebutton.html)
Setting setOnCheckedChangeListener will allow you to change the string.
String toggleisChecked;
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//Set the string to true
toggleIsChecked = "true";
} else {
// Set the string to false
toggleIsChecked = "false";
}
}
});
I'm not quite sure from your question whether you're also asking how to combine two values into the same string so the quickest explanation is to create a String in your resources such as:
<string name="current_states">%1$s & %2$s</string>
Then when setting that string you would add your two values like so:
String whateverYouWantToShow;
whateverYouWantToShow = getString(R.string.current_states, SelectedServer, toggleIsChecked);
This places the values into the string resource.
Hope this helps!

android radiobutton check after clearing check issue

friends. I'm having a really silly problem with radiogroup. Yet I'm unable to find solution.
I will try to describe how to reproduce my problem:
I have radiobutton group and two buttons inside.
I select one of them, lets say 1st one.
Then I'm clearing selection by calling radioGroup.clearCheck()
After I'm trying to select 1st button, but its not checking.
If I check 2nd, it checks normally.
If I check 1st after checking 2nd it also works normally.
This may sound crazy, yet I can't fix it. Please help me, thanks in advance.
I use
#Override
protected void init() {
View view = View
.inflate(getContext(), R.layout.wo_task_yn_result, null);
performed = (RadioButton) view.findViewById(R.id.yn_yes);
notPerformed = (RadioButton) view.findViewById(R.id.yn_no);
radioGroup = (RadioGroup) view.findViewById(R.id.yn_options);
performed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
Log.d(YES, "verify");
if (isChecked) {
Log.d(YES, "checked");
result = YES;
}
}
});
notPerformed.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView,
final boolean isChecked) {
Log.d(NO, "verify");
if (isChecked) {
Log.d(NO, "checked");
result = NO;
}
}
});
addView(view);
}
To create buttons and
#Override
public void clear() {
radioGroup.clearCheck();
result = "";
}
for clearing them
I had the same problem. Was unable to select the first radioButton in the group, but could select the other two. And after selecting the second radioButton, I could select the first one as well. I resolved it by doing a single radioGroup.clearCheck() instead of individual radioButtonA.setChecked(false)
Use OnCheckedChangeListener and make use of the method setSelected(true) or setChecked(true).
if u want to uncheck radio button try this method:
#Override
public void clear() {
performed.setChecked(false);
nonperformed.setChecked(false);
}

Smooth way to set all other togglebuttons to unchecked when one is checked

I specifically didn't want to use a radiogroup. I know, I know ... a radiogroup is perfect when you need exclusivity like this.
But..given that I'm working with togglebuttons, how can i disable (setChecked(false)) all (3) other toggle buttons when one of them is checked?
Here is my code for the group of toggle buttons. You need to put your
buttons in the layout where you want them and then use ToggleButtonsGroup object to put them together in a single group.
private class ToggleButtonsGroup implements OnCheckedChangeListener {
private ArrayList<ToggleButton> mButtons;
public ToggleButtonsGroup() {
mButtons = new ArrayList<ToggleButton>();
}
public void addButton(ToggleButton btn) {
btn.setOnCheckedChangeListener(this);
mButtons.add(btn);
}
public ToggleButton getSelectedButton() {
for(ToggleButton b : mButtons) {
if(b.isChecked())
return b;
}
return null;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
uncheckOtherButtons(buttonView.getId());
mDataChanged = true;
} else if (!anyButtonChecked()){
buttonView.setChecked(true);
}
}
private boolean anyButtonChecked() {
for(ToggleButton b : mButtons) {
if(b.isChecked())
return true;
}
return false;
}
private void uncheckOtherButtons(int current_button_id) {
for(ToggleButton b : mButtons) {
if(b.getId() != current_button_id)
b.setChecked(false);
}
}
}
I think you'll need to implement your own radiogroup logic for that. It will need to register itself as the OnCheckedChangeListener for each button it manages.
I wish the API wasn't designed with RadioGroup as a LinearLayout. It would have been much better to separate the radio group management from layout.
I know this has been answered with very good examples, but the way I set mine up is just a tad different so I thought I'd share. It's on a preference list, no ToggleButtonsGroup involved.
#Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals("trailPref") || key.equals("obstaclesPref") || key.equals("insanePref") || key.equals("backgroundBlackPref"))
{
if (key.equals("insanePref"))
{
endurancebox.setChecked(false);
prefsEditor.putBoolean("obstaclesPref", false);
prefsEditor.commit();
}
if (key.equals("obstaclesPref"))
{
insanebox.setChecked(false);
prefsEditor.putBoolean("insanePref", false);
prefsEditor.commit();
}
boolean b = ((CheckBoxPreference) preference).isChecked();
prefsEditor.putBoolean(key, b);
prefsEditor.commit();
}
Log.i(DEBUG_TAG, "Boolean value changed. " + key );
returnPrefs(c);
return false;
}
Also, I'm an Android noob and not too experienced in java either, so it may not be uber efficient, but hey, it works! Could be formatted easily to fit your needs I believe. If the key equals insanePref, I want to turn off obstaclesPref and vice versa. (different game modes, only one can be active at the time.) The other two booleans are unrelated. Also, it puts the preferences into my SharedPreference file, instantiated earlier, along with everything else.
Cheers!

Categories

Resources