Swodniw Swodniw - 2 years ago 90
Java Question

How to manage async task in Android

In my activity, I use a thread to call a server and receive an XML response I put on internal storage.

After this call, I read this xml file to parse it and show information about this xml file to the user but when I add this file in my InputStream, this InputStream is null.

I guess my activity continue the simple execution and dont wait my thread so when I create my InputStream, my xml file doesn't exist.

I made this schema corresponding to the execution of my program:

Schema here

How can make my activity wait the end of my thread? I know this is not a good thing to freeze the main activity but I don't know how i can do.
Can I add a waiting progress bar until the end of the thread with an observer on my thread?

PS: My thread implements Runnable

/*************EDITED WITH SOLUTION*************/

First, thanks to all for your responses it makes me progress a lot.

//In my Activity

MyAsyncTask asyncTask = new MyAsynctask();

//My Async class
public class MyAsynctask extends AsyncTask<Void,Void,Void> {

protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "calling server...", Toast.LENGTH_LONG).show();

protected Void doInBackground(Void... params) {

//Instance of calling class
//Method of this instance to call the server and create a file in internal storage
//After that my file is stored with the server response
return null;

protected void onPostExecute(Void result){

Toast.makeText(getApplicationContext(), "Data received", Toast.LENGTH_LONG).show();

FileInputStream inputStream = null;
inputStream = openFileInput("myFile");


I hope this post and your responses will be useful.

Answer Source
 public void onCreate(Bundle savedInstanceState) {
            new DownloadfromInternet().execute(server_url);


// Async Task Class class DownloadFromInternet extends AsyncTask {

    protected void onPreExecute() {
        // Shows Progress Bar Dialog and then call doInBackground

    // Download  File from Internet
    protected String doInBackground(String... f_url) {

        try {
        //make server call and store file in local
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        return LOCAL_FILE_NAME;

    protected void onPostExecute(String local_file_url) {
        // read local_file_url

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download