Dialog Fragment on a fragment with screen rotation

In my main action, I have a fragment in which I use setRetainInstance (true), so the AsyncTask used in it is not violated by a change of orientation.

A lot of work is handled by AsyncTask. Therefore, I would like to display a dialog with progressBar on top of my activity.

I did some research and managed to do it using DialogFragment:

Public class DialogWait extends DialogFragment {

private ProgressBar progressBar; public DialogWait() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_wait, container); Dialog dialog = getDialog(); dialog.setTitle("Hello"); setCancelable(false); progressBar = (ProgressBar) view.findViewById(R.id.progress); return view; } public void updateProgress(int value) { progressBar.setProgress(value); } 

And here is my AsyncTask:

 public class InitAsyncTask extends AsyncTask<Void, Integer, Void> { private Context activity; private OnTaskDoneListener mCallback; private DialogWait dialog; public InitAsyncTask(Context context, OnTaskDoneListener callback, DialogWait dialogWait) { activity = context; mCallback = callback; dialog = dialogWait; } @Override protected Void doInBackground(Void... params) { doStuff(); return null; } @Override protected void onProgressUpdate(Integer... values) { dialog.updateProgress(values[0]); } @Override protected void onPostExecute(Void result) { publishProgress(100); if(dialog != null) dialog.dismiss(); mCallback.onTaskDone(); } private void doStuff() { //... } 

}

If I do not change the rotation of the screen, it works fine. But if I do this, the dialog will be fired, and after a few seconds I get a NullPointerEsception, which is pointless since I set the condition: if (dialog! = Null)

What am I doing wrong?

+4
source share
2 answers

Solution found!

I did not do the right thing with the Snippet containing my AsyncTask.

Because I did not quite understand the concept of orientation in the Fragment, I get this thanks to this link: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

+3
source

Override the onCreate and onDestroyView methods in DialogWait as follows:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) { getDialog().setDismissMessage(null); } super.onDestroyView(); } 
+1
source

Source: https://habr.com/ru/post/1490971/


All Articles