Life of Apps

Smooth User Experience through AsyncTask

I was looking at the examples in the Android Developer site for connecting to the web and found the Network Connect sample. It illustrates how to use a HTTPURLConnection class and fetch details from the stream. While tinkering with the sample code, I moved the code from the AsyncTask to the main class. The gist is shown below.
   public boolean onOptionsItemSelected(MenuItem item) {
                try{
                    URL url = new URL("https://news.google.com");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 .... 
                    conn.connect();
                    InputStream stream = conn.getInputStream();
                }
                catch (Exception e){
                    Log.e(TAG, e.toString());
                }
                
 return true;
    }
When I ran the code, I got an exception - android.os.NetworkOnMainThreadException.What this essentially means is that we cannot do any time consuming operations, such as connecting to the network or loading large images on the main thread, as these would ruin the user experience of the app. So, Google has mandated (quite rightly so) to use the AsyncTask class which helps in doing operations in the background. So, in the AsyncTask class the key methods that help us are doInBackground and onPostExecute. We need to extend the AsyncTask class and override the doInBackground and onPostExecute methods. Key points and steps: When extending the AsyncTask class, the parameters should match the methods' return types. doInBackground will execute the logic onPostExecute will have the results Parameter of onPostExecute should match the return type of doInBackground; in this case both are Strings Instantiate the class that extends AsyncTask in the main class and call the execute method passing the arguments of the doInBackground method
    private class WebDataLoaderTask extends AsyncTask {

        @Override
        protected String doInBackground(String... urls) {
            try {
                    URL url = new URL("https://news.google.com");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 .... 
                    conn.connect();
                    InputStream stream = conn.getInputStream();
 ...
     return new String(buffer); 
                }
                catch (Exception e){
                    Log.e(TAG, e.toString());
                }
        }

        @Override
        protected void onPostExecute(String result) {
 //results are available here 
 Log.i(TAG, result);
        }
    }
The earlier code now looks like this:
   public boolean onOptionsItemSelected(MenuItem item) {
                try{
     new WebDataLoaderTask().execute("https://news.google.com");
                }
                catch (Exception e){
                    Log.e(TAG, e.toString());
                }
                
 return true;
    }
By moving to the AsyncTask based approach the android.os.NetworkOnMainThreadException is gone and the app provides a good user experience.

Danesh

Visit Pleb.in for apps developed by Danesh

No comments :

Post a Comment

Leave a Comment...