Question

I'm using an AsyncTask to grab some data from the web, but it still seems to be hanging the UI while fetching the data.

My code: https://gist.github.com/MasterEjay/10005933

The ThreadParse class is inside my main class, and the initWebView method is also inside of the main class, not ThreadParse.

Was it helpful?

Solution

You should launch the ASynctask using execute method.

With your code you just call the method in the main thread. execute will create a new thread for the Asynctask.

public void initWebView(String link) {
    ThreadParse parse = new ThreadParse();
    parse.execute(link);
}

If you really need to do something to the UI in doInBackground you should use runOnUIThread

I taked this code block as example

catch (IndexOutOfBoundsException ex){
    currentPage = 1;
    totalPages = 1;
    Toast.makeText(Thread.this, "You are on " + currentPage + " of " + totalPages, Toast.LENGTH_LONG).show();
    webview.loadDataWithBaseURL("http://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css", e.html(), "text/html", "utf-8", null);
    return;
}

Here, to let it work you should do

catch (IndexOutOfBoundsException ex){
    YourTopActivity.this.runOnUiThread(new Runnable()
    {
        currentPage=1;
        totalPages=1;
        Toast.makeText(Thread.this,"You are on "+currentPage+" of "+totalPages,Toast.LENGTH_LONG).

        show();

        webview.loadDataWithBaseURL("http://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css",e.html(),"text/html","utf-8",null);
    });
    return;
}

Same for other things which works with UI elements.

runOnUiThread documentation.

Here YourTopActivity is needed because you should use runOnUiThread method of Activity and you are inside Asynctask class.

Anyway, you should rethink your code to use onPostExecute and onPreExecute

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top