Using the selected state of a Android Toggle button / switch - android

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!

Related

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.

Multiple Switch.setTextOn() not updating switch's text

I have two Switchs buttons in my android Activity.
Both have custom dynamic On/Off texts (that are set at runtime with Switch.setTextOn(CharSeq) ).
They look like this (image found on another SO thread):
The first switch's on/off texts are set once.
My goal is to dynamically modify the on/off texts of the second switch, when the state of the first switch changed.
So I set up a OnCheckedChangeListener on the first switch like this:
switch2.setTextOff("ImOff"); // works, the text is updated on the switch
switch2.setTextOn("ImOn"); // same here
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(!isChecked)
{
switch2.setTextOff(myStrings.get(2));
switch2.setTextOn(myStrings.get(3)); // here switch2.getTextOn() returns the value of myStrings.get(3), but the widget still displays ImOn...
} else
{
switch2.setTextOff(myStrings.get(4));
switch2.setTextOn(myStrings.get(5)); // here switch2.getTextOn() returns the value of myStrings.get(5), but the widget still displays ImOn...
}
// I tried to update the switch with this and this
switch2.invalidate();
switch2.setChecked(valuesSwitch.isChecked());
}
});
But this code doesn't work, the on/off texts of the second switch are set on the object (getTextOn/Off returns the right text), but widget still displays the initial text ImOn/ImOff ...
Any ideas? Thanks.
I found a solution in this link,
https://groups.google.com/forum/#!topic/android-developers/1IYypcoYXlk
In a derived class (Which extends switch), override the Following method:
Override
public void request layout () {
try {
java.lang.reflect.Field mOnLayout = Switch.class.getDeclaredField ( "mOnLayout");
mOnLayout.setAccessible (true);
mOnLayout.set (this, null);
java.lang.reflect.Field mOffLayout = Switch.class.getDeclaredField ( "mOffLayout");
mOffLayout.setAccessible (true) ;
mOffLayout.set (this, null);
} Catch (Exception ex) {
Log.e (TAG, ex.getMessage (), ex);
}
super.requestLayout ();
}

saving the state of radiobuttons

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.

Android: Save State of Radio Buttons

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages and questions. For this task I have defined a radiogroup with some radiobuttons. What I want to obtain is each question answered radiobutton and when the user goes thorugh differentes pages the value can be retrieved. I have tried this code that consists of that if there is one selected radiobutton, there arent created new radiobuttons (radiobuttons checked false). However with this code, there is always a selected answer so there is always the same radiobutton selected. I will appreciate some help.
radBotA.setOnCheckedChangeListener(radioCheckChangeListener);
radBotB.setOnCheckedChangeListener(radioCheckChangeListener);
radBotC.setOnCheckedChangeListener(radioCheckChangeListener);
radBotD.setOnCheckedChangeListener(radioCheckChangeListener);
radBotA.setOnClickListener(radioClickListener);
radBotB.setOnClickListener(radioClickListener);
radBotC.setOnClickListener(radioClickListener);
radBotD.setOnClickListener(radioClickListener);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
bPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = position -1;
questions.Previous();
currentQuestion();
}
});
bNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
position = position +1;
questions.Next();
currentQuestion();
}
});
private void currentQuestion() {
if (position==0){
bPrevious.setVisibility(View.GONE);
}else{
bPrevious.setVisibility(View.VISIBLE);
}
if (position==nPreguntas-1){
bNext.setVisibility(View.GONE);
}else{
bNext.setVisibility(View.VISIBLE);
}
questions.currentQuestion(this, category);
enunciado.setImageResource(Enunciado[position]);
pregunta.setText(questions.getPregunta());
final RadioButton radBotA = new RadioButton(this);
final RadioButton radBotB = new RadioButton(this);
final RadioButton radBotC = new RadioButton(this);
final RadioButton radBotD = new RadioButton(this);
radBotA.setText("A. " + questions.getRespuestaA());
radBotB.setText("B. " + questions.getRespuestaB());
radBotC.setText("C. " + questions.getRespuestaC());
radBotD.setText("D. " + questions.getRespuestaD());
String nprueba = "Item " + questions.getId() + " de "+ nPreguntas;
NombrePrueba.setText(nprueba);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
}
thank you all for your time
Edit:
public void save(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
SharedPreferences.Editor e = settings.edit();
e.putBoolean("A0",radBotA.isChecked());
e.putBoolean("B0",radBotB.isChecked());
e.putBoolean("C0",radBotC.isChecked());
e.putBoolean("D0",radBotD.isChecked());
e.putBoolean("A1",radBotA.isChecked());
e.putBoolean("B1",radBotB.isChecked());
e.putBoolean("C1",radBotC.isChecked());
e.putBoolean("D1",radBotD.isChecked());
e.putBoolean("A2",radBotA.isChecked());
e.putBoolean("B2",radBotB.isChecked());
e.putBoolean("C2",radBotC.isChecked());
e.putBoolean("D2",radBotD.isChecked());
e.putBoolean("A3",radBotA.isChecked());
e.putBoolean("B3",radBotB.isChecked());
e.putBoolean("C3",radBotC.isChecked());
e.putBoolean("D3",radBotD.isChecked());
public void load(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA0 = settings.getBoolean("A0", false);
boolean answerB0 = settings.getBoolean("B0", false);
boolean answerC0 = settings.getBoolean("C0", false);
boolean answerD0 = settings.getBoolean("D0", false);
boolean answerA1 = settings.getBoolean("A1", false);
boolean answerB1 = settings.getBoolean("B1", false);
boolean answerC1 = settings.getBoolean("C1", false);
boolean answerD1 = settings.getBoolean("D1", false);
boolean answerA2 = settings.getBoolean("A2", false);
boolean answerB2 = settings.getBoolean("B2", false);
boolean answerC2 = settings.getBoolean("C2", false);
boolean answerD2 = settings.getBoolean("D2", false);
boolean answerA3 = settings.getBoolean("A3", false);
boolean answerB3 = settings.getBoolean("B3", false);
boolean answerC3 = settings.getBoolean("C3", false);
boolean answerD3 = settings.getBoolean("D3", false);
However I don't know how to continue. I v' thinking about the following code but it gives me error and where posicion is the "Page Number":
public void Test(){
switch(posicion){
case(0):
if(answerA0==true){
e.putBoolean("A0",radBotA.isChecked());
}
}
}
}
If I understand you correctly, you want to retrieve some data in other activities. In that case the easiest way would be to use SharedPreferences.
After user answers the question (CheckBox's check state is being changed) you should store your information in SharedPreferences like this:
SharedPreferences settings = getSharedPreferences("Answers", 0); // first argument is just a name of your SharedPreferences which you want to use. It's up to you how you will name it, but you have to use the same name later when you want to retrieve data.
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("questionA", radBotA.isChecked()); // first argument is a name of a data that you will later use to retrieve it and the second argument is a value that will be stored
editor.putBoolean("questionB", radBotB.isChecked());
editor.putBoolean("questionC", radBotC.isChecked());
editor.putBoolean("questionD", radBotD.isChecked());
editor.commit(); // Commit the changes
So now you have those information stored in your internal storage. In other activity, you can retrieve this information:
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA = settings.getBoolean("questionA", false); // The second argument is a default value, if value with name "questionA" will not be found
boolean answerB = settings.getBoolean("questionB", false);
boolean answerC = settings.getBoolean("questionC", false);
boolean answerD = settings.getBoolean("questionD", false);
I'm working on same application and the solution is that you have to store state of Radio button according to your question Number and for each question there is different key, like this:
final RadioButton rdSelection=(RadioButton)findViewById(mradioOptGroup.getCheckedRadioButtonId());
int child_index=mradioOptGroup.indexOfChild(rdSelection);
switch(mid)
{
case 1:
sharedpreferences.putint("",child_index);
break;
case 2:
sharedpreferences.putint("",child_index);
break;
}
and do like this for all your questions on every next question
and on every previous question you have to store state of radio button of mid+1
where mid is your question number
i just solved this problem , now i am able to save the current state of radio button on every next click and on every previous click i get back the radio state,even at the if the user changed the state by going to previous question or any of the question.

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