Thursday, January 13, 2011

Consuming REST Web Service using Android

In this tutorial, we will find out how to create an Android application to consume REST Web Service.

We will create android application which will consume web service in this post .
Our application should look like this.

Create a new Android Application named "Note Android".
Modify AndroidManifest and add INTERNET permission.

Next, create the view for posting new note : main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Note Id" />
<EditText android:id="@+id/txtId"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:text="Content"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="@+id/txtContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:id="@+id/btnPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post" />
<Button android:id="@+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View All" />
</LinearLayout>
view raw main.xml hosted with ❤ by GitHub


And the view for viewing all of our notes. There is no component here. Only a layout because we will create the component programmatically

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>
view raw view.xml hosted with ❤ by GitHub


Next, create our view for posting note : DatabaseAndroid.java

package com.tukangjava.tutorial;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DatabaseAndroid extends Activity
implements View.OnClickListener {
String urlPost = "http://203.247.166.88:8000/NoteWS/notes";
TextView txtId;
TextView txtContent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeGUI();
}
private void initializeGUI() {
Button btnPost =(Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
Button btnView =(Button)findViewById(R.id.btnView);
btnView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.btnPost)
postData();
startActivity(new Intent(this, ViewDatabase.class));
}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlPost);
txtId = (TextView) findViewById(R.id.txtId);
txtContent = (TextView) findViewById(R.id.txtContent);
try {
// Add the data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("noteId", txtId.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("content", txtContent.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("createddate", new Date().getTime() + ""));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
Log.w("ERROR", e.getMessage());
} catch (IOException e) {
Log.w("ERROR", e.getMessage());
}
}
}


And the code for parsing xml retrieved from web service and present each element on a TextView : ViewDatabase.java

package com.tukangandroid.tutorial;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class ViewDatabase extends Activity
implements View.OnClickListener{
String url = "http://203.247.166.88:8000/NoteWS/notes";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
retrieveData(ll);
this.setContentView(sv);
}
private void retrieveData(LinearLayout ll) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
DocumentBuilder builder;
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpGet, responseHandler);
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=builder.parse(new InputSource(new StringReader(responseBody)));
NodeList ids =doc.getElementsByTagName("noteId");
String[] allIds = new String[ids.getLength()];
for (int i=0;i<ids.getLength();i++) {
Element elem = (Element)ids.item(i);
allIds[i] = elem.getFirstChild().getNodeValue();
}
NodeList contents =doc.getElementsByTagName("content");
String[] allContents = new String[contents.getLength()];
for (int i=0;i<contents.getLength();i++) {
Element elem = (Element)contents.item(i);
allContents[i] = elem.getFirstChild().getNodeValue();
}
NodeList createddates =doc.getElementsByTagName("createdDate");
String[] allCreateddates = new String[createddates.getLength()];
for (int i=0;i<createddates.getLength();i++) {
Element elem = (Element)createddates.item(i);
allCreateddates[i] = elem.getFirstChild().getNodeValue();
}
for (int i=0;i<allIds.length;i++) {
TextView id = new TextView(this);
id.setText(allIds[i]);
ll.addView(id);
TextView content = new TextView(this);
content.setText(allContents[i]);
ll.addView(content);
TextView createddate = new TextView(this);
createddate.setText(allCreateddates[i]);
ll.addView(createddate);
View view = new View(this);
view.setBackgroundColor(Color.WHITE);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
ll.addView(view);
}
Button b = new Button(this);
b.setOnClickListener(this);
b.setText("Post New");
ll.addView(b);
} catch (ClientProtocolException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (IOException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (SAXException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (ParserConfigurationException e) {
Log.e(getString(R.string.app_name), e.getMessage());
} catch (FactoryConfigurationError e) {
Log.e(getString(R.string.app_name), e.getMessage());
}
}
@Override
public void onClick(View v) {
startActivity(new Intent(this, DatabaseAndroid.class));
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


Run our application and try creating new notes.

Have fun!

5 comments:

  1. Hello
    When i have tried above code and customize according to my web service and when i click on post button it shows return in response "bad request 400". can you please help me.

    ReplyDelete
  2. hi tom,
    can u pls help me out..i am getting connection refused in log file wen i try to post a note..how can get over this???

    ReplyDelete
  3. can u provide the .zip source code???????????????

    ReplyDelete
    Replies
    1. u cant code!!!!!

      why u need the .zip source code????

      don't be lazy.

      Delete
    2. Is there any problem with u??
      Then why u r behaving so rude??
      If .zip code has been provided u will be the 1st to download it....

      Delete