Cosmin Pârvulescu
Cosmin Pârvulescu

Reputation: 324

How should I refactor my code in order to avoid the Network on Main Thread exception on Android?

In my MainActivity I have a class initialization like so:

Presentation presentation = new Presentation("link");

Presentation is a class which gets initialized using values from a .JSON file on a web server:

public Presentation(String URL) {
    // Do stuff
    doNetworking();
}
private doNetworking() {
    // Network access here
    // This throws the Network on Main Thread exception
}

In my MainActivity, I need all the values of Presentation to be there in the next step:

Presentation presentation = new Presentation();
// Do some stuff with it

Using the AsyncTask I am not sure how I should go about doing this, so far I have something like this: public Presentation(String URL) { // Do stuff new InitializePresentation().execute(URL); }

private class InitializePresentation extends AsyncTask<String, Void, Boolean> {
    // Amongst other things
    protected Boolean doInBackground(String... params) {
        // Do the networking stuff here
    }
}

What I need is to refactor this code so that it is asynchroneous but behaves like a synchroneous call. Any help is greatly appreciated.

edit How does one refactor a code to accomplish this?

Bitmap b = new Bitmap();
Load bitmap from network;
Use bitmap in imageview;

Can this be used in this fashion? Or do I have to use it like

Async, doInBackground() {
   Load bitmap from network
   Use bitmap in imageview
   Continue with application
}

Thank you!

Upvotes: 0

Views: 95

Answers (1)

Nermeen
Nermeen

Reputation: 15973

You can show a progress dialog while doing the network stuff:

private ProgressDialog progressDialog;
private Context context;

public InitializePresentation (Context context) {
    this.context = context;
}

@Override
protected void onPreExecute() {
    progressDialog = ProgressDialog.show(context, "", "loading", true);
}

/* 
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected String doInBackground(String... arg0) {
    // Do the networking stuff here
}

@Override
protected void onPostExecute(final String result) {
    progressDialog.dismiss();
}

Upvotes: 2

Related Questions