Calling RESTful Web Services in Android

androidWeb services make it easy for mobile devices to communicate with applications running on a web or application server. I am sharing how to implement an Android client for services implemented according to the REST approach. This tutorial shows how you send HTTP requests, parse JSON string responses and display the results in a ListActivity, showing a progress dialog while loading.

Already I have written a Restful web services using PHP and MySQL. You can refer here.

This file contain Asyncronous server request to get json data and parse that json data.

1. List Items:

ListItemsActivity.java


package com.chitta.androidapps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
 
public class ListItemsActivity extends ListActivity {
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    ArrayList<HashMap<String, String>> productsList;
 
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_items);
 
        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();
 
        // Loading products in Background Thread
        new LoadAllItems().execute();
 
    }
 
    /**
     * Background Async Task to Load all items by making HTTP Request
     * */
    class LoadAllItems extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ListItemsActivity.this);
            pDialog.setMessage("Please wait items loading ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            
           
            String result = null;
            InputStream is = null;
            StringBuilder sb = null;
            
         // Http connection to php file
            try{
                   HttpClient httpclient = new DefaultHttpClient();
                       //testing on Emulator
                   
                   String url = "http://10.0.2.2/slimf/api/items";
                   
                   HttpGet httpget = new HttpGet(url);
                    
                   HttpResponse response = httpclient.execute(httpget);
                   HttpEntity entity = response.getEntity();
                   is = entity.getContent();
               }catch(Exception e){
                   Log.e("log_tag", "Error in http connection"+e.toString());
               }
    
               //convert response to string
               try{
                    
               BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                   sb = new StringBuilder();
                   sb.append(reader.readLine() + "\n");
                   String line="0";
                  
                   while ((line = reader.readLine()) != null) {
                       sb.append(line + "\n");
                   }
                     
                   is.close();
                   result = sb.toString();
                     
               }catch(Exception e){
                   Log.e("log_tag", "Error converting result "+e.toString());
               }
                
                
              String name, id;
                
               try{
                   JSONArray jArray = new JSONArray(result);
                   JSONObject json_data = null;
                     
                   for(int i = 0; i < jArray.length(); i++){
                           json_data = jArray.getJSONObject(i);
                           

                           id = json_data.getString("id");
                           name = json_data.getString("name");
                           //Log.d("Product Name: ", name);

                           // creating new HashMap
                           HashMap<String, String> map = new HashMap<String, String>();
    
                           // adding each child node to HashMap key => value
                           map.put("id", id);
                           map.put("name", name);
    
                           // adding HashList to ArrayList
                           productsList.add(map);
                           
                            
                   }
                     
                   }catch(JSONException e1){
                       Toast.makeText(getBaseContext(), "No User Found", Toast.LENGTH_LONG).show();
                   }catch (ParseException e1){
                       e1.printStackTrace();
                   } 
               
           
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            
         // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ListItemsActivity.this, productsList,
                            R.layout.list_items, new String[] { "id",
                                    "name"},
                            new int[] { R.id.id, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
 
        }
 
    }
    
   
} 

layout/all_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    

 
</LinearLayout>

layout/list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
 
    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />
 
    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" />
 
</LinearLayout>

Well, your App will need to connect to the internet in order to request your web services. This requires the permission android.permission.INTERNET.

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

2. Add Item:
Here I have not implemented layouts/GUI. Just added http POST sample code.

try{
            HttpClient httpclient = new DefaultHttpClient();
                //testing on Emulator
            
            String url = "http://10.0.2.2/slimf/api/items";
            
            HttpPost httppost = new HttpPost(url);
         
            JSONObject json = new JSONObject();

            // just passing static item name for add
            json.put("name", "testitem");
            
            httppost.setHeader("Content-type", "application/json");
            httppost.setEntity(new StringEntity(json.toString(), "UTF-8"));
            
            HttpResponse response = httpclient.execute(httppost);
            
            if (response.getStatusLine().getStatusCode() != 201) {
		throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
				}
} catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }
 

2. Edit Item:
Just added http PUT sample code.

try{
            HttpClient httpclient = new DefaultHttpClient();
                //testing on Emulator
                // just passing item id 3 as static to edit item
            String url = "http://10.0.2.2/slimf/api/items/3";
           
            HttpPut httpput = new HttpPut(url);
         
            JSONObject json = new JSONObject();

         // just passing static item name for edit
            json.put("name", "PHP item edit");
            
            httpput.setHeader("Content-type", "application/json");
            httpput.setEntity(new StringEntity(json.toString(), "UTF-8"));
            
            HttpResponse response = httpclient.execute(httpput);
} catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }            
 

4. Delete Item:
Just added http DELETE sample code.

try{
            HttpClient httpclient = new DefaultHttpClient();
                //testing on Emulator
            // just passing item id 3 as static to delete item
            String url = "http://10.0.2.2/slimf/api/items/3";
            
           
            HttpDelete httpdelete = new HttpDelete(url);
           
            HttpResponse response = httpclient.execute(httpdelete);
            
            if (response.getStatusLine().getStatusCode() != 204) {
					throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
			}
 
            
        } catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }

 

Run your project and test the application. You might get lot of errors. Always use Log Cat to debug your application, and if you couldn’t solve your errors please do comment here.

Advertisements

One thought on “Calling RESTful Web Services in Android

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s