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.
Related
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();
}
}
I have a NavigationDrawer in my Activity with three items.
I want to show all three items when first time user Login.
In other session I want to make one item invisible and show only two items in NavigationDrawer.
you have to detect first launch of the app using this code
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
add 1 item to navigation drawer at first launch or after first launch is completed, remove your 1 of the item from navigation drawer
USE SharedPreferences to store user status!
public class SharedPrefModel {
public static String INFO_STORE_TAG = "user_info";
public static String sharedPrefName = "USER";
private SharedPreferences sharedPref;
public SharedPrefModel(Context context) {
this.sharedPref = context.getSharedPreferences(sharedPrefName, MODE_PRIVATE);
}
public void setStatus(Boolean isFirstTime) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(INFO_STORE_TAG, isFirstTime);
editor.apply();
}
public Boolean getStatus() {
return sharedPref.getBoolean(INFO_STORE_TAG,false);
}
public void clearInfo() {
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.apply();
}
}
After login for the first time set the status to false.
new SharedPrefModel(this).setStatus(false);
Next Time check that if the status is true or not.
if(!new SharedPrefModel(this).getStatus()){
//hide
}
to reset the status! use
new SharedPrefModel(this).clearInfo();
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”));
}
scenario during a simple ball game i click exit and return to the menu and then exit out of the app,once i launch the app again I can click 'Continue" from the main menu and return to the game where i had left off or click New game and start again.
My problem is get sharedprefs are on onCreate, so even if i click 'New game' it continues from where i had left off.
I tried various onclick, findviewbyid methods and none of them worked, for example.
public class GActivity extends ActionBarActivity {
private int RWIDTH = 70;
// + a whole bunch of other unrelated stuff that i cut-out to make viewing easier.
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button CntButton = (Button) findViewById(R.id.ConGame);
CntButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
RWIDTH = settings.getInt("RWIDTH", RWIDTH);
}
});
}
protected void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("RWIDTH", RWIDTH);
editor.commit();
}
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