maysara
maysara

Reputation: 6429

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 !?

Upvotes: 6

Views: 2525

Answers (2)

Stanislav Ur
Stanislav Ur

Reputation: 1

Same problem Try to change to this

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

Upvotes: 0

adelphus
adelphus

Reputation: 10316

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

Upvotes: 15

Related Questions