Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - losing variables data when partially closing an app

I am using a class with static values called DB (for Data Base) in my application. When I first run the app, a static byte array from this class is filled and used. Then, when I partially close my app (not closing it definitily just put in background) if a reopen it after 20 seconds more or less, the value of the variable is still here but if I let my app in the background for more than 1 minute the value turns to null.

How can I avoid this to happen?

like image 305
Roman Panaget Avatar asked Mar 10 '26 12:03

Roman Panaget


2 Answers

store your variable value to shared preferences and load the value from shared preferences in the onResume() Method of activity and store the value in the onPause() Method.

like image 50
Deepak Goyal Avatar answered Mar 13 '26 02:03

Deepak Goyal


Handling lifestyle events properly is an important aspect of Android development.

I suggest that you read the following to make sure that you understand what happens to your app when you turn off your screen, change to another application or any other action that might change the state of your app:

http://developer.android.com/training/basics/activity-lifecycle/index.html

My suggestion is to store your data by overriding onSaveInstanceState() like so:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) 
{
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Then on your onCreate(), you can reload it like so:

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) 
    {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } 
    else 
    {
        // Probably initialize members with default values for a new instance
    }
...
}

I hope that this helps!

Good luck in your future developing!

like image 23
Adam Avatar answered Mar 13 '26 01:03

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!