Tag Archives: AsyncTask

Android AsyncTask

I have seen with many apps that the main thread is sometimes (ab)used by doing too many asynchronous tasks in it. This is very easily resolved by making use of the AsyncTask class in android.os.AsyncTask.

A simple example. Let us assume that you want to call a set of WordPress REST URL’s and get a bunch of JSON back to work with. This is actually really simple and non-blocking if you do it properly with AsyncTask.

The key here is that you need to subclass all of your calls with AsyncTask calls.The class will need to override at least one method

doInBackground(Params ...)

and in some cases, you will probably want to override

onPostExecute(Result)

.

I think that the method names are sufficient description for what they do in this case.

With that in mind, let’s create our “Task” class:

package com.myapp.tasks;

import java.util.ArrayList;
import java.util.List;

import com.myapp.PostLister;
import com.myapp.model.PostInfo;

import de.akquinet.android.androlog.Log;
import android.os.AsyncTask;

public class PostListTask extends AsyncTask<String, Integer, List<PostInfo>> {

	private static final String TAG = "PostListTask";

	@Override
	protected List<PostInfo> doInBackground(String... params) {
		List<PostInfo> posts = new ArrayList<PostInfo>();
		for (String urlid : params) {
			PostLister postlist = new PostLister();
			PostInfo post = postlist.getURL(urlid);
			posts.add(post);
		}
		if (isCancelled()) {
			Log.e(TAG, "User cancelled listing " + params);
		}
		Log.i(TAG, "Post list done..");
		return posts;
	}
}

Once that is done, we need to fill in the missing classes

package com.myapp;

import org.json.JSONException;
import org.json.JSONObject;

import com.myapp.model.PostInfo;
import com.myapp.util.JSONParser;

public class PostLister {

	public static final String url="http://paulscott.co.za/blog/wp-json.php/posts/";
	public static final String urlid = "";
	public static final String TAG_CONTENT = "content";
	public static final String TAG_TITLE = "title";
	public static final String TAG_LINK = "link";
	public static final String TAG_ID = "ID";
	public static final String TAG_SLUG = "slug";
	public static final String TAG_DATE = "date";

	JSONParser jParser = new JSONParser();
	
	public PostInfo getURL(String urlid) {
		JSONObject json = jParser.getJSONFromUrlByGet(url+urlid);
		try {
			String str_content = json.getString(TAG_CONTENT);
			String str_title = json.getString(TAG_TITLE);
			String str_link = json.getString(TAG_LINK);
			String str_ID = json.getString(TAG_ID);
			String str_slug = json.getString(TAG_SLUG);
			String str_date = json.getString(TAG_DATE);
			PostInfo post = new PostInfo(str_content, str_title, str_link, str_ID, str_slug, str_date);
			return post;
		} catch (JSONException e) {
			// whatever...
		}
		return null;
		
	}
}

As you can see, we are only using a few fields from the JSON produced by the WP-JSON plugin, but you get the gist right?

Now for a model

package com.myapp.model;

public class PostInfo {
	
	private String content;
	private String title;
	private String link;
	private String id;
	private String slug;
	private String date;
	
	public PostInfo(String content, String title, String link, String id,
			String slug, String date) {
		super();
		this.content = content;
		this.title = title;
		this.link = link;
		this.id = id;
		this.slug = slug;
		this.date = date;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getLink() {
		return link;
	}

	public void setLink(String link) {
		this.link = link;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getSlug() {
		return slug;
	}

	public void setSlug(String slug) {
		this.slug = slug;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}	
}

Pretty standard stuff.

Once we are ready to fire it off, we simply invoke the AsyncTask with

AsyncTask<String, Integer, List<PostInfo>> posts = new PostListTask().execute("492", "491");

Which you can pretty much do whatever you want with:

try {
        	List<PostInfo> res = posts.get();
        	for(PostInfo post : res) {
        	    String content = post.getContent();
        	    Log.d(TAG, content);
        	}
        } catch (InterruptedException e) {
        	e.printStackTrace();
        }
        catch (ExecutionException e) {
        	e.printStackTrace();
        }

Where the String array we send is a list of the posts that we want to retrieve.

Dead simple, fast and efficient! Yay!