How to handle ToggleButton state in OnPause and OnResume state - android

I am facing problem with toggle button state on onResume() and onPause() state.
Activity - A (first user toggle ON the button) then go back to Activity - B, then it will comeback to Activity - A then I want toggle Button is ON not OFF, how to handle this state in android.

By default Activity handles its components state which has an id attribute.
If it's not acting like that, you can use onSaveInstanceState and onRestoreInstanceState to handle components state manually:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("Toggle1", toggle.isChecked());
// etc.
}
And to restore the state:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean toggle1State = savedInstanceState.getBoolean("Toggle1");
toggle1.setCheched(toggle1State);
}

toggle_relative.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
#Override
public void onToggle(boolean on) {
if (on == true){
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("toggle_relative", true); // value to store
editor.commit();
Toast.makeText(getContext(),"Relatives will be notified in case of accidental situation",Toast.LENGTH_LONG).show();
}else {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("toggle_relative", false); // value to store
editor.commit();
}
}
});
#Override
public void onResume() {
super.onResume();
boolean boll_toggle_relative = preferences.getBoolean("toggle_relative", false); //default is true
if (boll_toggle_relative == true)
{
toggle_relative.setToggleOn();
}
else
{
toggle_relative.setToggleOff();
}
}

Related

Android ToggleButton toggle state issue

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

Saving State Of Activity Android

How can I save state of activity that setBackgroundResource and setTextColor I have set up in if sentence remains changed when I start activity again?
if (cases == 1) {
TextView layout = (TextView) findViewById(R.id.textView1);
layout.setBackgroundResource(R.drawable.izbrano);
layout.setTextColor(Color.parseColor("#d7a308"));
ImageView image = (ImageView) findViewById(R.id.imageOdprto);
image.setImageResource(R.drawable.o1);
String strIi = formatter.format(cases);
text.setText(strIi + "€");
}
It seems that you need to store settings instead of the Activity's state. In this case I would suggest using SharedPreferences.
Maybe it is more easy just to remember your cases value (assumed it is global):
#Override
public void onPause(){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("cases", cases);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
cases = sharedPref.getInt("cases", 0);
if ( cases == 0 ){
// do stuff
} else {
// do more stuff
}
}
Using preferences is not much more preferred.
Here is a nice tutorial for how to save activity states. Check this Link
it suggests,
int someVar;
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("someVar", someVar);
outState.putString(“text”, tv1.getText().toString());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
someVar = savedInstanceState.getInt("someVar", 0);
tv1.setText(savedInstanceState.getString(“text”));
}

Load preferences in another activity?

I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

Android : Shared preferences inside tabhost not working

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.

save the state when back button is pressed

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setOnClickListener(this);
LoadPreferences();
s1.setEnabled(false);
}
public void SavePreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", s1.isEnabled());
}
public void LoadPreferences()
{
System.out.println("LoadPrefe");
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
s1.setEnabled(state);
}
#Override
public void onBackPressed()
{
System.out.println("backbutton");
SavePreferences();
super.onBackPressed();
}
What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
you can use this way
public void onBackPressed() {
// Save settings here
};
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
save your application state in this method.

Categories

Resources