Why is it necessary to check savedInstanceState inside of OnCreate? [duplicate] - android

This question already has answers here:
What's onCreate(Bundle savedInstanceState)
(5 answers)
Closed 7 years ago.
What is the purpose of the if block in the onCreate() method? Why is it necessary to check if savedInstanceState is null?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}

When your activity is recreated, such as after a screen rotation or other configuration change, fragments are automatically reattached. By checking if savedInstanceState == null, you ensure that you are not re-adding a fragment that has already been added for you.

Well that's so you can remember where someone was when they last left your app. So for instance chrome remembers your last visited tabs.

Related

cant find code which changes Fragment

I'm working on my app since a few weeks. Now i pointed out the bug, that if i rotate my Device, it always replaces my Fragment to the "Home-Fragment".. and i dont know why. I Was searching it with "find in path"-function in Android Studio. I searched for keywords like:
-orientation
-setOrientation
-Landscape
-Portrait
But didnt find the code-snippet which changes my Fragment on rotation...
Any tipps? How can i find out where the "fragment replace" gets called?
the correct code to initialise the "home fragment" is like this:
public class MyActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new HomeFragment())
.commit();
}
}
}
note that you only do the fragment transaction if savedInstanceState == null, if it's not null, the Android and Fragment frameworks will automatically recreate everything.
I'm pretty sure the reason that you're always replacing with the homeFragment is because you're not checking savedInstanceState == null
Add android:configChanges="orientation|screenSize" to the manifest in your activity. This will prevent your activity to recreate view after orientation changes.

Understanding how AndroidStudio generated code restores a PlaceholderFragment

I created a test application using AndroidStudio, selecting an activity with a fragment. What I do not understand is how the PlaceholderFragment is restored when savedInstanceState is not null, taking into account that setContentView is called after super.onCreate().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
Hello the savedInstanceState is only not null when you rotated the device. When the activity recreate it should load from savedInstanceState. by the way the code you are talking about is part of android activity not android studio. Thank you.

findFragmentByID() returns null using container ID immediately after it is created

Note I've checked the very numerous "duplicates" of this question and none of them fit the bill, so please don't mark this as a duplicate.
I modified the default wizard-created app (in Android Studio) to try to find the placeholder fragment after it is created, like this (the only statement added is the Log line):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Log.d("", "Found fragment: " + getSupportFragmentManager().findFragmentById(R.id.container));
}
However the log just prints:
Found fragment: null
According to what I've read of the documentation and answers to similar questions, it should work. What's going on?
The fragment transaction has not yet been executed but just scheduled for later execution.
Wait for super.onStart() in the application lifecycle, of if you're impatient, call executePendingTransactions().

Is it a good pratice to restore savedInstanceState?

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
// processing
}
Is it a good practice to avoid processing further if the savedInstanceState is not null?
does this have any drawback?
I expect this code is not what you want as there can be different times you want to have savedInstanceState so if it is set pull out the data you will have saved so the user has the same state though they may have rotated their phone.
You may want to look at this question and answers
What's onCreate(Bundle savedInstanceState)

Fragment saveInstanceState is coming as null after orientation change

I have an activity with action bar tab. Each tab contain a fragment. Now when I rotate my device, bundle in my corresponding fragment is coming as null. This is taken care when I using device post android 3.2, but it is happening when device is Andoird3.0. I am having a headache after working on this issue. I crossed check various link on SO, but no help. Although I have given enough details, still will provide some code snippet as at various cases user ask for code snippet.
In my fragment class I am storing this value
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("textboxVisible", true);
}
this is storing one boolean variable which it retrived as below.
/**
* Function called after activity is created. Use this
* method to restore the previous state of the fragment
*/
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
{
//restore the state of the text box
boolean textboxVisible = savedInstanceState.getBoolean("textboxVisible");
if (textboxVisible)
{
//do some stuff
}
}
}
but after rotation savedInstanceState is coming as null.
I don't what is going wrong. I have read in some document that below 3.2 the onCreateView() of
fragment is not called with bundle value. But to deal with this. Any help will be appreciated.
if you use setRetainInstance(true) the savedInstance bundle is always gonna be null after orientation changed. SO you cannot really save something with it, but what you can do if you need to save something, is to put it in a data member of the fragment, because setRetainInstance(true) preserves the fragment and doesn't destroy it, so after the device was rotated you gonna have the same values.
Try to get the savedInstanceState in onCreate of the Fragment.
Like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if (savedInstanceState != null) {
// IT MUST NOT BE NULL HERE
}
}
Please try... i hope it will work

Categories

Resources