I have a section of my UX flow where I want to display a message for the user in a textview for 2 seconds in fragment A, and after that replace fragment A with fragment B. I accomplish this by doing as follows from within fragment A.
someTextView.setText("some message");
Handler mainLooperHandler = new Handler(Looper.getMainLooper());
mainLooperHandler.postDelayed(new Runnable() {
@Override
public void run() {
((MyActivity) getActivity()).gotoTheNextFragment();
}
}, 2000);
And in my activity the relevant method:
public void gotoTheNextFragment() {
Fragment mFragmentB = new FragmentB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, mFragmentB, "FRAGMENTB")
.commit();
}
However this causes a few issues. First of all, if the user presses 'back' while the postdelayed is executing then the user gets a null pointer exception on getActivity. Second, the user sometimes gets the error "Can not perform this action after onSaveInstanceState" while trying to perform the transfer.
I know that if I change the 'commit' to 'commitAllowingStateLoss' then I'll avoid the second error, but this probably isn't best practice and I know that moving between fragments at all inside an asynctask isn't recommended. What is a better way of accomplishing this process (showing the message, waiting two seconds, and then replacing the fragment in a safe way that won't lead to crashes)?