In my application, I always need to execute some stuff at the first time the app is open. When user opens it, the app shows a dialog with a progressbar, while executes an AsyncTask
on background, and after (on onPostExecute()
) i need to commit a Fragment
.
So, in my Main Activity
's onCreate()
method, I have:
public class InitialActivity extends SherlockFragmentActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
if(savedInstanceState == null) //Executes just at the firstTime
{
//ApplicationStarter -> It manages all execution to start my app, executes asynctask, shows dialogs..
ApplicationStarter starter = new ApplicationStarter(this) {
@Override
public void afterFinish() {
//It Executes at onPostExecute when doInBackground() finishes
ItensFragment itensfrag = new ItensFragment();
frag.setTargetFragment(itensfrag , 0);
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.simple_fragment, itensfrag);
ft.commitAllowingStateLoss();
}
};
starter.start();
}
}
}
So, everything goes Ok, but the app crashes if user rotates the device or after onDestroy()
method is called. The following exception is launched:
java.lang.IllegalStateException: Activity has been destroyed
at ft.commitAllowingStateLoss();
I searched around and I found on this post that it isn't a good practice to perform a Fragment
transiction inside asynchronous callback methods like i am trying to do.
And i saw this answer too, that maybe i could adapt to my case. But before that, i would like to know if anyone has a better way or suggestion for what i'm trying to do.
Thanks in advance.