Reputation: 4557
Here are some facts about my app followed by a question
My app has two fragments.
My app creates certain file structure and documents on its first launch and it takes time, thus I am using AsyncTask
class method to display ProgressDialog
while the file structure is created. This is done in onCreate
method of my MainActivity just like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progress = new ProgressDialog(this);
progress.setMessage("Loading...");
File testFile = new File("/mnt/sdcard/myNewFolder");
if (!testFile.exists()) {
new MyTask(progress).execute();
setContentView(R.layout.activity_main);
} else
setContentView(R.layout.activity_main);
}
The problem is that onActivityCreated
method of one of my Fragment
s starts running BEFORE new MyTask(progress).execute();
is finished. This causes errors and problems.
Why this onActivityCreated
method of one of my Fragment
s runs BEFORE
new MyTask(progress).execute();
???
Please do not assume that there are some silly mistakes that i didnt take into account xx
This is my MyTask class
public class MyTask extends AsyncTask<Void, Void, Void> {
public MyTask(ProgressDialog progress) {
// this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public void onPostExecute(Void unused) {
progress.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
CreateFileStructure();
return null;
}
}
I need to create that file structure before anything else happens - that is why I am using this ProgressDialog
. What am I doing wrong?
Upvotes: 0
Views: 816
Reputation: 4557
Here is the code that works for me - the ProgressDialog
dialog is displayed while file structure and files are created, everything else (fragments, etc.) happens afterwards.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progress = new ProgressDialog(this);
progress.setMessage("Loading...");
File testFile = new File("/mnt/sdcard/myNewFolder");
if (!testFile.exists())
new MyTask(progress).execute();
else
setContentView(R.layout.activity_main);
}
public class MyTask extends AsyncTask<Void, Void, Void> {
public MyTask(ProgressDialog progress) {
// this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public void onPostExecute(Void unused) {
progress.dismiss();
setContentView(R.layout.activity_main);
}
@Override
protected Void doInBackground(Void... params) {
CreateFileStructure();
return null;
}
}
Upvotes: 0
Reputation: 2824
If you see the life cycle of fragment, the view of the fragment's are instantiated on the onCreate method of the activity which contains the fragment.
For that reason you are getting that error.
Upvotes: 1