I am new to android. I am creating a app which uses a toggle button. I want the toggle button to do some tasks when the button is in checked state and do some another tasks when the button is unchecked. And I want the toggle button to retain its state even when the user closes the app(by pressing back switch) and comes back. I managed to get it done by using shared preference, but the problem is that when the user turns the toggle button on and goes back and come back again, the tasks are getting done again. Is there any way to retain my toggle button on state, and not to the tasks associated with it?? And sorry for my bad English :)
public class MainActivity extends AppCompatActivity {
ToggleButton onoff;
public static Bundle bundle=new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onoff = (ToggleButton) findViewById(R.id.toggleButton);
onoff.setChecked(false);
onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// do some tasks here
} else {
//do some tasks here
}
}
});
}
#Override
public void onPause(){
super.onPause();
bundle.putBoolean("ToggleButtonState", onoff.isChecked());
}
#Override
public void onResume(){
super.onResume();
if(bundle.getBoolean("ToggleButtonState",false))
{
onoff.setChecked(true);
}
}
}``
Simply add another condition to your OnCheckedChangeListener:
onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked && !bundle.getBoolean("ToggleButtonState",false) {
// do some tasks here
} else if(!isChecked){ //optional + , your preference on what to to :)
//do some tasks here
}
}
});
So, when you return, and your button is checked, but your saved boolean is also true, it will not execute your task.
Edit:
For use with onSaveInstanceState :
In your activity, add the following method:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("ToggleButtonState", onoff.isChecked());
super.onSaveInstanceState(outState);
}
And retrieve this boolean in onCreate(), under findViewById(...):
boolean checkedStatus = savedInstanceState.getBoolean("ToggleButtonState", false);
onoff.setChecked(checkedStatus);
For additional Information visit Recreating an Activity
Related
I have an issue like selecting and unselecting a single radio button on click, the setOnCheckChangeListner() works only for the first time below is the code which I have tried.
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) radioButton.setChecked(false);
else radioButton.setChecked(true);
}
});
I have made a solution for it using set selected attribute of the radio button.
final RadioButton radioButton = findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!radioButton.isSelected()) {
radioButton.setChecked(true);
radioButton.setSelected(true);
} else {
radioButton.setChecked(false);
radioButton.setSelected(false);
}
}
});
try to use preference xml this one is essay to save the click events.because its like small db.
How to create RadioButton group in preference.xml window?
You are generating a endless loop. That will cause stackoverflow error.
Because you are changing radio button checked status inside onCheckedChanged.
If you need changing check status then do it in click of a button.
Don't change check status inside onCheckedChanged
Perhaps you need to change status of RadioButton for some condition. For that you will do following.
public class MainActivity extends AppCompatActivity {
RadioButton radioButton = null;
CompoundButton.OnCheckedChangeListener listener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO: 8/6/2018 your logics
}
};
radioButton.setOnCheckedChangeListener(listener);
changeStatus(radioButton, true);
}
private void changeStatus(RadioButton radioButton, boolean status){
radioButton.setOnCheckedChangeListener(null);
radioButton.setChecked(status);
radioButton.setOnCheckedChangeListener(listener);
}
}
When you need to change status then call
changeStatus(radioButton, true);
The layout of my app contains a TextView and a toggle Button. When the toggle Button is turned ON an AlertDialog appears and the user is prompted to give the time for the countdown to start. It works fine if I dont change the orientation while it counts down. However when I change orientation while the countdown keeps running the Dialog Box reappears which shouldn't. I know that changing orientation destroys and recreates my activity so given the fact that toggle button was ON before the activty is destroyed when it is recreated it continuous to be ON as it should be. So my question is if there is a way for the AlertDialog not to appear after the orientation change.
I have tried adding the following but it didnt work
Declared as class variable
public static final String TOGGLE_BUTTON_STATE = "OFF";
Trying to set the toggle Button to true
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: created.............");
mTextTime = (TextView) findViewById(R.id.textView);
mToggleButton = (ToggleButton) findViewById(R.id.toggleButton);
if((savedInstanceState != null) && TOGGLE_BUTTON_STATE.equals("ON")) {
Log.d(TAG, "onCreate: created after changing orientation........");
mToggleButton.setChecked(true);
}
mToggleButton.setOnCheckedChangeListener(this);
saving the state before it is destroyed
#Override
public void onSaveInstanceState(Bundle outState) {
if(mToggleButton.isChecked()) {
Log.d(TAG, "onSaveInstanceState: toggleButton is checked...........****");
outState.putString(TOGGLE_BUTTON_STATE, "ON");
}else {
Log.d(TAG, "onSaveInstanceState: toggleButton is not checked...........*****");
outState.putString(TOGGLE_BUTTON_STATE, "OFF");
}
super.onSaveInstanceState(outState);
}
//Listener for the ToggleButton
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Toast.makeText(this, "ON", Toast.LENGTH_SHORT).show();
// TOGGLE_BUTTON_ON = true;
//getting the xml user_input to java
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.user_input, null);
//search inside the view for the text_input
mTextUserInput = (EditText) view.findViewById(R.id.text_input);
//We create the builder and we use it to add functionality to the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Enter The Time");
//We create the user_input that has only the editext widget that we gonna use to get the
//time from the user
builder.setView(view);
builder.setPositiveButton("OK", this);
builder.setNegativeButton("Cancel", this);
builder.show();
} else {
// OFF selected and timer must stop
// TOGGLE_BUTTON_ON = false;
timer.stop();
}
}
ps The countdown timer keeps running properly even after orientation change
Your way of loading the previously stored state in onCreate is false. You are saving the state correctly (but i would prefer storing it as a boolean) - but you are not reading it correctly from the savedInstance.
The way i would do it:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("TOGGLE_BUTTON_STATE", mToggleButton.isChecked());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(savedInstanceState != null) {
mToggleButton.setChecked(savedInstanceState.getBoolean("TOGGLE_BUTTON_STATE"));
}
mToggleButton.setOnCheckedChangeListener(this);
...
}
You can dismiss the alert dialog when the activity is going to be destroyed.
For example:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
...
// Save the dialog in an instance variable
mDialog = builder.show();
}
#Override
public void onStop() {
if (mDialog != null) {
mDialog.dismiss();
}
super.onStop();
}
I currently am developing an app that has a menu, and one of the options on the menu is "Settings" where the user can basically decide to turn off sounds and other things like that. I currently have two switches in the Settings activity. Here is the java code for the Settings activity so far:
public class Options extends ActionBarActivity {
private Switch ding;
private Switch countdown;
public boolean isDingChecked;
public boolean isCountdownChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
ding = (Switch) findViewById(R.id.switch1);
AppPreferences appPref;
appPref = new AppPreferences(getApplicationContext(), "PREFS");
appPref.SaveData("Value", "Tag");
appPref.getData("state");
if(appPref.getData("state").equals("true"))
{
ding.setChecked(true);
}
else if(appPref.getData("state").equals("false"))
{
ding.setChecked(false);
}
ding.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(ding.isChecked())
{
ding.setChecked(true);
}
}
});
countdown = (Switch) findViewById(R.id.switch2);
countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
isCountdownChecked = isChecked;
}
});
}
}
However, if I go back to the menu activity and then go back to the options activity, the switch's values go back to the default value. Is there a way I can save the state between different activities? Thanks!
You can use SharedPreferences.
Store it:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("StringName", "StringValue");
// Commit the edits!
editor.commit();
Recover it:
SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
String silent = settings.getString("StringName", "DefaultValueIfNotExists");
You can also put and recover booleans and integers and others...
http://developer.android.com/reference/android/content/SharedPreferences.html
I have a tabhost with three activities and I want to save the pressed state of the buttons of each activity
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other the button pressed state will be reflected on moving back. first activity -> all 4 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state
When I go to second child tab and come to the first child tab the change(The buttons which I pressed are not in pressed state) is not reflecting
Help is always appreciated , Thanks
this is my code in first tabhost child activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seatdirnbtn.setOnClickListener(listner1);
seatdirnbtn1.setOnClickListener(listner2);
seatdirnbtn.setPressed(true);
seatdirnbtn1.setPressed(true);
this.LoadPreferences();
}
private void SavePreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", seatdirnbtn.isEnabled());
editor.putBoolean("state1", seatdirnbtn1.isEnabled());
editor.commit();
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
Boolean state = sharedPreferences.getBoolean("state", false);
Boolean state1 = sharedPreferences.getBoolean("state1", false);
seatdirnbtn.setPressed(state);
seatdirnbtn1.setPressed(state1);
}
#Override
protected void onStart() {
super.onStart();
LoadPreferences();
}
#Override
protected void onPause() {
SavePreferences();
super.onPause();
}
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
isclick = !isclick;
}
};
private View.OnClickListener listner2 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2hlt);
} else {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2);
}
isclick = !isclick;
}
};
probably you should override onResume() method in which you should set buttons states. this method is called after onCreate() and even the activity is already created. If you have activities in tabHost they are not created each time you switch between tabs so onCreate() method will be called only once but onResume() every time you switch to tab with particular activity.
your code which is loading preferences is in onStart() method. Look here on activity lifecycle. You can see that this method is called only if your activity was stopped before but will never called if it was just paused.
EDIT:
if you have just 2 states like in your code from question it could be better to use ToggleButton which also generally have 2 states. You can style it to have different backgrounds for each state. This tutorial could be helpfull.
Than you will have a little bit different Listener:
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(checked) {
//do sth if it's checked
} else {
//do sth if it's not checked;
}
}
});
to change states for them programatically:
toggleButton.setChecked(true); //or false
so finally you can save this state to SharedPreferences:
editor.putBoolean("toggleButton1",toggleButton.isChecked());
and when you will need this state:
boolean isChecked = sharedPreferences.getBoolean("toggleButton1",false);
toggleButton.setChecked(isChecked);
selector will take care of switching button backgrounds for each state.
I have implemented an application for save the properties of android content view.
I have used check box for enable and disable a editText.When user check the the check box then i am enabling edit text view and when user unchecked the check box then disabling edit text.Here if user check the check box then edit text view will be enable for enter data then the user click on save button then the edit field propertie as enabling will save if user re lunch the app
I have implemented code for it as follows:
((EditText)findViewById(R.id.editText1)).setEnabled(false);
((CheckBox)findViewById(R.id.checkBox1)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
((EditText)findViewById(R.id.editText1)).setEnabled(true);
}
else{
((EditText)findViewById(R.id.editText1)).setEnabled(false);
}
}
});
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//here how to save the properties of editText1 and checkBox1 upto re-launch
}
});
If user re open the application the modified content only will appear.
Please any body help me....
Try something like this:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("editTextState", editText.isEnabled());
outState.putBoolean("checkBoxState", checkBox.isEnabled());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
editText.setEnabled(savedInstanceState.getBoolean("editTextState"));
checkBox.setEnabled(savedInstanceState.getBoolean("checkBoxState"));
}
}
Or you can use SharredPreferences.
In your Activity:
private EditText editText;
private CheckBox checkBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
checkBox = (CheckBox) findViewById(R.id.checkBox1);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
editText.setEnabled(true);
} else {
editText.setEnabled(false);
}
}
});
loadProperties();
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveProperties();
}
});
}
private void saveProperties() {
SharedPreferences.Editor editor = getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit();
editor.putBoolean("CHECK_BOX_STATE", checkBox.isChecked());
editor.putBoolean("EDITEXT_STATE_STATE", editText.isEnabled());
editor.commit();
}
private void loadProperties() {
SharedPreferences prefs = getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE);
checkBox.setChecked( prefs.getBoolean("CHECK_BOX_STATE", false));
editText.setEnabled( prefs.getBoolean("EDITEXT_STATE_STATE", false));
}
What you need to use is:onSaveInstanceState(android.os.Bundle)
This method makes it possibile to save for example all information of your controls.
Another possibility would be to use SharedPreferences
SharedPreferences settings = this.context.getSharedPreferences("myPreferences", 0);
// read stored value
String storedValue = settings.getString("aKey", null);
// store/override value
SharedPreferences.Editor editor = settings.edit();
editor.putString("aKey", "aValue");
editor.commit();