Anjan Kailash
Anjan Kailash

Reputation: 63

savedInstanceState is always null value in onCreate

This is my onCreate method in a class which is subclass of fragment

static  int counter = 0;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) { //made for first time
        Log.d("came in", "Came in");
        counter = 0;
    } else {
        counter = savedInstanceState.getInt("counter", 0);
    }
}

this is my savedInstanceState method

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    Log.d("hi there", ""+counter); // this is printing hi there 3
    outState.putInt("counter", counter);//key value pair
}

but in onCreate method savedInstanceState is always null and printing came in.

Upvotes: 0

Views: 2192

Answers (3)

Konstantin
Konstantin

Reputation: 184

try change you method onSaveInstanceState to:

@Override
public void onSaveInstanceState(Bundle outState){    
    Log.d("hi there", ""+counter); // this is printing hi there 3
    outState.putInt("counter", counter);//key value pair
    super.onSaveInstanceState(outState); // call super after put int
}

Upvotes: 0

Ambar Jain
Ambar Jain

Reputation: 517

Try to save your value in your fragment host activity(Activity in which your fragment is defined). From host activity, you have to extract that value and access it in your fragment subclass.

Upvotes: 0

dumb_terminal
dumb_terminal

Reputation: 1825

Override protected void onRestoreInstanceState(Bundle savedInstanceState) and see if you can get your values there.

Upvotes: 1

Related Questions