Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSaveInstanceState doesn't work

when screen rotates ... Toast print nothing !

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String a  = savedInstanceState.getString("hello");
    Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    String a = "WTF";
    outState.putString("hello",a);
}

}

I declared everything nicely,, where is the bummer in this simple code !?

like image 215
Maysara Alhindi Avatar asked May 13 '16 20:05

Maysara Alhindi


1 Answers

I think you've fallen into a really common trap many devs have since the Android OS team overloaded the onSaveInstanceState() method.

You are overriding the wrong method. The one you want is:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String a = "WTF";
    outState.putString("hello",a);
}

Personally, I think Craig Mautner should be forced to donate money every time an Android developer makes this mistake - source

like image 52
adelphus Avatar answered Oct 12 '22 03:10

adelphus