Android Fragment Communication onSaveInstanceState

In this tutorial we cover android fragment communication onSaveInstanceState. Point is to save counted number in the fragment and reuse it again when mobile device is rotated. Starting from previous example, add in “Upper” fragment onSaveInstanceState method.

onSaveInstanceState-in-Upper-Fragment

Now, add more code with value-key pair. Key is string, and value in this example is int.
outState.putInt(“counter”,count);
Further code change in “Upper” fragment is to create onCreate method.

out-state-in-onSaveInstanceState-and-onCreate

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState==null)

{

count = 0;

}

else

{

count = savedInstanceState.getInt(“counter”,0);

}

}

if-savedInstanceState-null

We need to make small changes in “Lower” fragment as well. Declare

public class Lower extends Fragment {

TextView text;

String takenData;

Then check if saved instance state is null and if is not fill takenData with previous value and declare Text View, and set its text with saved data.

String-takenData

You can download Android Fragment Communication onSaveInstanceState

External links:

Android Fragment Communication onSaveInstanceState on Youtube
Android Fragment Communication onSaveInstanceState on Stackoverflow

 

Posted in android Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

*