Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7937213
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T22:28:04+00:00 2026-06-03T22:28:04+00:00

This is the first time I used AsyncTask and it works but it’s very

  • 0

This is the first time I used AsyncTask and it works but it’s very dirty as I just copied and pasted some code. I want to do it the right way and as clean as possible. So can anyone help me with cleaning up my code and tell me how to do it the right way? You would do me a great favor in helping me and giving me more experience in future Android developing. I want to learn it the right way from the start 😉

EDIT:
After reading a bunch of tutorials and watching video’s I think I made an huge improvement! And I’m very happy I did it! But there’s only one small problem left. At the startup of the app, it doesn’t load the page. The shouldOverrideUrlLoading works great after I clicked a link but at the startup it shows only a blank screen. What’s the problem?

public class WebviewActivity extends MainActivity {

    private WebView myWebView;
    private ProgressDialog progressDialog;
    private boolean mConnection = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final ScrollView mainScrollView = (ScrollView)findViewById(R.id.ScrollView01);

        myWebView = (WebView)findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                new checkConnection().execute();
                if (mConnection == true){
                    view.loadUrl(url);
                }           
                return true;                
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                mainScrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        });

        myWebView.requestFocus(View.FOCUS_DOWN);
        myWebView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_UP:
                        if (!v.hasFocus()) {
                            v.requestFocus();
                        }
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();       
        new checkConnection().execute();
        if (mConnection == true){
            myWebView.loadUrl(webLink);
        }
    }

    //------------------------------------------------------
    //-----DOING THE CONNECTION CHECK IN ANOTHER THREAD-----
    //------------------------------------------------------

    public class checkConnection extends AsyncTask<Void, Void, Void>{

        int mStatusCode = 0;
        Exception mConnectionException;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();           
            progressDialog = ProgressDialog.show(WebviewActivity.this, "", "Loading...", true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
                    URL url = new URL(webLink);
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
                    urlc.connect();

                    mStatusCode = urlc.getResponseCode();

                    if (mStatusCode == 200){
                        //Nothing to do.
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                mConnectionException = e;
            }
            return null;
        }   

        @Override
        protected void onPostExecute(Void param){
            progressDialog.dismiss();

            if (mStatusCode  == 200){
                mConnection = true;
            }
            else if (mStatusCode  == 404){
                myWebView.loadUrl("file:///android_asset/errorpage404.html");
            }
            else {
                myWebView.loadUrl("file:///android_asset/errorpage.html");
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T22:28:06+00:00Added an answer on June 3, 2026 at 10:28 pm

    Please, don’t call progressDialog.dismiss(); from doInBackground(), use onPostExecute() instead. doInBackground() is not an UI thread, so trying to manipulate UI elements might give you wild consequences.

    Here’s why you don’t get your page loaded on the first try:

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                new checkConnection().execute();  <- (1)
                if (mConnection == true){         <- (2)
                    view.loadUrl(url);
                }           
                return true;                
    

    (1) starts asynchronous task, which is going to be finished some time in the future
    (2) tries to check the results of (1) immediately, so there are no results yet.


    here’s modified version of your AsyncTask, which accepts url as a parameter:

    public class checkConnection extends AsyncTask<String, Void, String>{     <------ change this
    
        int mStatusCode = 0;
        Exception mConnectionException;
    
        @Override
        protected void onPreExecute(){
            super.onPreExecute();           
            progressDialog = ProgressDialog.show(WebviewActivity.this, "", "Loading...", true);
            progressDialog.show();
        }
    
        @Override
        protected Void doInBackground(String... params) {     <------ change this
            try {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
                if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
                    URL url = new URL(webLink);
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
                    urlc.connect();
    
                    mStatusCode = urlc.getResponseCode();
    
                    if (mStatusCode == 200){
                        //Nothing to do.
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                mConnectionException = e;
            }
            return params[0];     <------ change this
        }   
    
        @Override
        protected void onPostExecute(String param){     <------ change this
            progressDialog.dismiss();
    
            if (mStatusCode  == 200){
                myWebView.loadUrl(param);     <------ change this
            }
            else if (mStatusCode  == 404){
                myWebView.loadUrl("file:///android_asset/errorpage404.html");
            }
            else {
                myWebView.loadUrl("file:///android_asset/errorpage.html");
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is the first time I've used a 3rd party jar, but it seems
This is the first time I've used pthreads. I'm having trouble because some times
I've used NSNotifications before but this is the first time I've tried to use
I've used CakePHP a few times before but this is the first time I'm
This is a really basic question but this is the first time I've used
This is the first time I got this error. This code basically gets the
This is the first time I've used @font-face. The font pack is from myfonts.com
This is the first time I've used interceptors with the fluent registration and I'm
This is the first time I've used a thread that requires returning values to
Today is the first time I've used Python, so I'm sure this'll be an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.