Can someone answer this question for me:
For testing purposes, I created an action with a for loop in which I create 10 AlertDialogs or 10 DialogFragments. Immediately after starting the activity, I press the "home" button to send the application in the background. If I run the showDialog () method to create a Dialog dialog box, the application will crash with:
IllegalStateException: Can not perform this action after onSaveInstanceState
this is the expected behavior.
But if I run the showAlert () method to create AlertDialogs and the same way as before sending the application to the background, the application does not crash. When I return to activity, I will see all 10 AlertDialogs.
The question is why does state loss happen with DialogFragment and not with AlertDialog?
I am still changing the user interface after maintaining the activity state. The platform I tested on is Android 4.4.2.
public class Main extends FragmentActivity { private FragmentActivity activity = this; private MyAsynk myAsynk; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); myAsynk = new MyAsynk(); myAsynk.execute(); } private class MyAsynk extends AsyncTask<Void, Void, Void> { private boolean run = false; public MyAsynk() { run = true; } @Override protected Void doInBackground(Void... params) { for(int i = 0; i < 10 && run; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
MyDialogFragment.java:
public class MyDialogFragment extends DialogFragment { private MyDialogFragment instance; public static MyDialogFragment newInstance(String text) { MyDialogFragment f = new MyDialogFragment(); Bundle args = new Bundle(); args.putString("text", text); f.setArguments(args); return f; } public MyDialogFragment() { instance = this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.my_dialog_fragment, container, false); TextView tv = (TextView) v.findViewById(R.id.tv); Button bu = (Button) v.findViewById(R.id.bu); bu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if(null != instance && instance.isVisible()) { instance.dismiss(); } } catch(Exception e) { e.printStackTrace(); } } }); tv.setText(getArguments().getString("text")); return v; } }
user1851615
source share