Swodniw Swodniw - 6 months ago 27
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();
asynctask.execute();

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

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

@Override
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;
}


@Override
protected void onPostExecute(Void result){
super.onPostExecute(result);

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

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

data=XMl.parse(inputStream);
}
}


I hope this post and your responses will be useful.

Answer
 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new DownloadfromInternet().execute(server_url);

        }

// Async Task Class class DownloadFromInternet extends AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Shows Progress Bar Dialog and then call doInBackground
    }

    // Download  File from Internet
    @Override
    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;
    }


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

    }
}
Comments