Android

Learn AsyncTask Implementation with Android App

Hello Developers !!!

In previous article, we understood the concept  of AsyncTask and had its simple implementation. Now we will study one more sample where AsyncTask can be used.  We are going to develope a App called “SayQuotes” ,where I am going to get quotes from blog using html parser and display it. So, Lets Start !!

To Achieve Application, We are going to need –

  • Any List of Text as Content
  • Content Extractor

Content :

We will use blog link: http://shrenoid.com/quotes/  for retrieving  content as List of Quotes .

Content Extracter :

The Webpage of link is in HTML Format. So we need to extract data from HTML Format Webpage. We are going to use library “jsoup-1.10.3.jar”.  You can download package/jar file from link.

Note: WE ASSUMED THAT INTERNET IS WORKING ON MOBILE PHONE BEFORE RUNNING APPLICATION. 

Implementation as below:

Step 1: copy the jsoup jar file to the  folder location- AndroidSudioProjects/Your Project Folder/app/libs

Step 2: Back to Android Studio, Now we are going to add jsoup library to Project Dependencies.

  1. Go to File -> Project Structure .
  2. Select app Module -> Dependencies -> ‘+’ -> Jar dependency
  3. Select the jar file we pasted in libs folder.
  4.  Press “OK” “OK” till Project Structure window is closed. Then Open file build.gradle (Module:app) file expanding the Gradle Scripts. And check compile files(‘libs/jsoup-1.10.3.jar) is added in dependencies and build the Gradle.Alternative: write this highlighted statement and build the gradle again.

Step 3: Now its time to design layout :

There will be a list of quotes .So we will be using List View .

Layout content_say_quotes.xml:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout tools:layout_editor_absoluteX="0dp" 
tools:layout_editor_absoluteY="81dp" 
tools:showIn="@layout/activity_say_quotes" 
tools:context="com.technogrill.apps.shrenoidcolours.SayQuotes" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
android:layout_height="match_parent" 
android:layout_width="match_parent" 
xmlns:tools="http://schemas.android.com/tools" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:android="http://schemas.android.com/apk/res/android">

<ListView android:id="@+id/listquotes" 
android:layout_height="match_parent" 
android:layout_width="match_parent"
android:dividerHeight="2dp"/>
</RelativeLayout>

To fill listview cell , I used Layout content_quotecell.xml :

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:padding="15dp" 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:orientation="vertical" 
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="@+id/tvquotecontainer" 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:text="Quote 1" 
android:textSize="20dp"/>
</LinearLayout>

Step 4:  Let’s move towards the code implementation:

a. Lets declare class objects :

  1. ListView Class object : To use and update the listview with the content.
  2. List<String> Class object: We will need list to hold the content.
  3. ArrayAdapter<String> Class object: We will require adapter to fill the content from List Array to List View.
  4. GetBlogQuotes Class object: This is class extended with AsyncTask class which is going to fetch the html site and extract data and add to list.
 ListView lstQuotes; 
 GetBlogQuotes getBlobList;
 List<String> lstQuotesContent;
 ArrayAdapter<String> adapterList;

b. Link the ListView class object:

        lstQuotes=(ListView)findViewById(R.id.listquotes);

c. Initialize List<String> object with one entry:

        lstQuotesContent=new ArrayList<>();
        lstQuotesContent.add("Quotes are as follows:");

d. Initialize ArrayAdapter object:

 adapterList = new ArrayAdapter<String>(SayQuotes.this,R.layout.content_quotecell, R.id.tvquotecontainer, lstQuotesContent);

e. Set ListView with Adapter:

lstQuotes.setAdapter(adapterList);

f. Initialize GetBlobQuotes Class Object :

 getBlobList =new GetBlogQuotes();
 getBlobList.execute(new String[]{"http://shrenoid.com/quotes/"});

g. Create a Inner Class GetBlobQuotes extending with AsyncTask <String,String,String>:

private class GetBlogQuotes extends AsyncTask<String,String,String>{
 @Override
 protected String doInBackground(String... params) {
 return null;
 }

 @Override
 protected void onPreExecute() {
 super.onPreExecute();
 }

 @Override
 protected void onPostExecute(String s) {
 super.onPostExecute(s);
 }

 }

h. Now, we are going to send parameter as string array with webpage url  and execute AsyncTask ,

 getBlobList =new GetBlogQuotes();
 getBlobList.execute(new String[]{"http://shrenoid.com/quotes/"});

i. Before way to writing the fetching method, we will study the code,

 

Note: If you want to see the webpage source code , Right click on it and select Inspect Code option.

For more jsoup reference, refer https://jsoup.org/ website.

j. The whole webpage source code is fetched using the get() method and stored in Document:

  Document document=Jsoup.connect(params[0]).get();

k. This jsoup.connect( Link Url in String format) throws IOExecption which is to handled using try-catch block.

l. Document is used to get Elements by tag /id or by class name. So, we will retrieve elements by class name for fetching blog title:

    document.getElementsByClass("entry-title") gets Element header <h> and using element.text() we receive text
    String blog_title=document.getElementsByClass("entry-title").text();

m. Next,As <div> with classname “entry-content” contains all <p> elements containing quotes, Document is used to retrieve element <div> by classname and stores as Elements (group of  <p> are fetched) .

Elements setofquotes=document.getElementsByClass("entry-content");

n. Now we need to retrieve each element <p> and store in List<String> lstQuotesContent,

     article_content=setofquotes.select("p").get(p_tag_i);
     lstQuotesContent.add(article_content.text());

o. Till content is fetched ,we implemented ProgressDialog Box in PreExecute() Method in AsyncTask

p. After code in doInBackground  method gets executed ,it goes on onPostExecute() method , Here ProgressDialog is dismissed , Toolbar title is updated and List is being updated so,we need to set adapter to notifyDataSetChanged() method  :

 adapterList.notifyDataSetChanged();

q. Now, let’s write GetBlogQuotes class,

private class GetBlogQuotes extends AsyncTask<String,String,String>{
 Document document;
 String blog_title="";
 Elements setofquotes;
 Element article_content;
 ProgressDialog dialog;
 
@Override
 protected String doInBackground(String... params) {
 try{
     document=Jsoup.connect(params[0]).get();
     blog_title=document.getElementsByClass("entry-title").text();
     setofquotes=document.getElementsByClass("entry-content");

     for(int p_tag_i=1;p_tag_i<=setofquotes.select("p").size()-1;p_tag_i++){
     article_content=setofquotes.select("p").get(p_tag_i);
     lstQuotesContent.add(article_content.text());
    
    }
   }catch (IOException ioexcp){
        ioexcp.printStackTrace();
       
   }
 return null;
 }

@Override
 protected void onPreExecute() {
 super.onPreExecute();
 dialog=new ProgressDialog(SayQuotes.this);
 dialog.setProgress(0);
 dialog.setMessage("Fetching Quotes..");
 dialog.setCancelable(false);
 dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 dialog.show();
}

@Override
 protected void onPostExecute(String s) {
 super.onPostExecute(s);
 if(dialog.isShowing())
 dialog.dismiss();
 getSupportActionBar().setTitle(blog_title);
 adapterList.notifyDataSetChanged();
}
}

r. Finally most important thing, We are accessing the online webpage , so we need to take permission in AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

We are done with this sample and implemented AsyncTask Background Process.  Hope you have understood the sample. You will have output like this:  Click Here to Get the Code

On Fetching Data
After Fetching Data

4 thoughts on “Learn AsyncTask Implementation with Android App”

  1. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our local library but I think I learned more clear from this post. I’m very glad to see such excellent info being shared freely out there.

Leave a Reply

Your email address will not be published. Required fields are marked *