0

My question is rather simple, but i can't handle with him. I have chronometer field in my design.

I want to save them for avoid lost value of time by revert the screen (recreate new activity)

I use for save

    public Object onRetainConfigurationInstance(){
    return timeSeconds;
}

And for reestablish timeSeconds = (Chronometer) getLastNonConfigurationInstance();

But it doesn't work. Could somebody help me? What parameter i must save for reestablish chronometer time?

user2105282
  • 724
  • 1
  • 12
  • 26

2 Answers2

2
protected void onSaveInstanceState(Bundle outState) {
    outState.putLong(TIME_KEY, timeSeconds.getBase());
    super.onSaveInstanceState(outState);
}

protected void onRestoreInstanceState(Bundle savedInstanceState){
    if((savedInstanceState !=null)
            && savedInstanceState.containsKey(TIME_KEY)){
        timeSeconds.setBase(savedInstanceState.getLong(TIME_KEY));
    }
    super.onRestoreInstanceState(savedInstanceState);
}
user2105282
  • 724
  • 1
  • 12
  • 26
1

You should probably use onSaveInstanceState() to save data between orientation changes, your code can look like this:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putLong("time_seconds", timeSeconds);
    super.onSaveInstanceState(outState);
}

Then you can get stored value inside the onCreate(), which is called as the Activity gets recreated when orientation changes:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    long timeSeconds = savedInstanceState.getLong("time_seconds");
    // other code from onCreate()
}
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Egor
  • 39,695
  • 10
  • 113
  • 130