in Tutorial

Android Asynchronous Http Client-A Callback-Based Http Client Library for Android and Android Smart Image View

In this tutorial i will introduce you the Android Asynchronous Http Client-A Callback-Based Http Client Library for Android and Android Smart Image View developed by James Smith (http://loopj.com/android-async-http/ and http://loopj.com/android-smart-image-view/). There is a good documentation for the libraries. This client is based on the Apache’s HttpClient. I will show downloading a JSON asynchronously and showing the JSON info on the screen. We will use the GSON library for json2object.
The JSON will hold the info of a Person as follows:
[sourcecode language=”java”]
public class Person {

public String name;
public String photoURL;

public Person() {

}

public Person(String name, String photoURL) {
this.name = name;
this.photoURL = photoURL;
}

}
[/sourcecode]
Setup the asynchronous http client as described in the documentation of the library. Put the jar files into the libs folder. We will develop a client and clientUsage class as described in the documentation as follows:
[sourcecode language=”java”]
public class MyRestClient {

private static final String BASE_URL = “http://myBaseURL”;
private static AsyncHttpClient client = new AsyncHttpClient();

public static void get(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {

client.get(getAbsoluteUrl(url), params, responseHandler);
}

public static void post(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}

private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}

public class MyRestClientUsage {

public void getPerson(String fileName,MyJsonHandler jsonHandler) throws JSONException {

MyRestClient.get(fileName, null,jsonHandler);
}
}
[/sourcecode]
Extend the JsonHttpResponseHandler class as follows:
[sourcecode language=”java”]
public class MyJsonHandler extends JsonHttpResponseHandler{

MainActivity activity;

public MyJsonHandler(MainActivity activity)
{
this.activity = activity;
}

@Override
public void onSuccess(JSONObject myobj) {

Gson gson = new Gson();
Type listType = new TypeToken<Person>() {}.getType();
String str = myobj.toString();

Person p = gson.fromJson(str,listType);
activity.onDownloadSuccess(p);
}

@Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
activity.onDownloadFailure();
}

}
[/sourcecode]
As you see in the code, we pass the activity as parameter to the handler class. In the onSuccess method, we get the JSON object, convert it to Person object and call the onDownloadSuccess method of our Activity and we call the onDownloadFailure method of our activity in the onFailure of handler class.

Here is the interface that our activity implements:
[sourcecode language=”java”]
public interface OnDownloadListener {

public void onDownloadSuccess(Person person);
public void onDownloadFailure();
}
[/sourcecode]

In the Activity class we firstly initialize the views, then initialize our rest client and start the download with getPerson method. In the onDownloadSuccess method, we get the JSON object and show it on the screen. As you see in the code, we use the SmartImageView , we set the image URL and it downloads the image asynchronously. Our Activity is as follows:
[sourcecode language=”java”]
public class MainActivity extends Activity implements OnDownloadListener {

TextView txtName;
SmartImageView imageView;
MyJsonHandler jsonHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txtName = (TextView) this.findViewById(R.id.textViewName);
imageView = (SmartImageView)this.findViewById(R.id.imageViewPhoto);

jsonHandler = new MyJsonHandler(this);
MyRestClientUsage client = new MyRestClientUsage();
try {
client.getPerson(“myJSON.json”, jsonHandler);
} catch (JSONException e) {

e.printStackTrace();
}
}

@Override
public void onDownloadSuccess(Person person) {

txtName.setText(person.name);
imageView.setImageUrl(person.photoURL);
}

@Override
public void onDownloadFailure() {
// TODO Auto-generated method stub

}

}
[/sourcecode]

Layout XML of the Activity is as follows:
[sourcecode language=”xml”]
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.MainActivity” >

<TextView
android:id=”@+id/textViewName”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:text=”@string/hello_world” />

<com.loopj.android.image.SmartImageView
android:id=”@+id/imageViewPhoto”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_above=”@+id/textViewName”
android:layout_centerHorizontal=”true”
android:src=”@drawable/ic_launcher” />

</RelativeLayout>
[/sourcecode]
Construct the JSON in UTF-8 because this client supports UTF-8 by default and i couldnt find a way to set the encoding of the client. Finally, dont forget to give internet access permission in the manifest.

Murat AYDIN
maydin (at) gmail.com

Written By:

Murat Aydin is a senior software engineer in a company that develops software technologies for defense systems, and is an enthusiastic Android developer. He has several Android applications in Google Play. He is a Sun Certified Java Developer and has eight years of experience in developing web based applications using Java technologies, and desktop and engineering applications using .Net technologies. Murat Aydin earned his BSc degree in Computer Engineering from METU (Middle East Technical University) and his MSc degree in Software Engineering from METU. He is a member of GDG Ankara (Google Developer Group Ankara, www.gdgankara.org), who organize several Android events in GDG Ankara, such as Android Developer Days. (www.androiddeveloperdays.com)

4 Comments

  1. prekast Mart 30, 2013 Reply
    • murat.aydinAuthor Mart 30, 2013 Reply
  2. curioso Mayıs 13, 2013 Reply
    • murat.aydinAuthor Haziran 7, 2013 Reply

Add a Comment

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