This tutorial about the Rest - WCF service usage in android. WCF is a tool often used to implement and deploy a service-oriented architecture (SOA). It is designed using service-oriented architecture principles to support distributed computing where services have remote consumers. Clients can consume multiple services; services can be consumed by multiple clients. Services are loosely coupled to each other.WCF supports XML, JSON and ATOM data formats. It faster than ASMX and supports scaling/load balance.We use mostly GET, POST, PUT and DELETE methods.
GET Method:
The HTTP GET method is used to retrieve/read a representation of a resource.
Sample Data Format:
The sample JSON data is below.
Code:
Now, read the data from server with simple HTTP Request and display the results with the help of Lazy Adapter.
We have to use StrictMode.ThreadPolicy method here. Because, the network operations (HTTPUrlConnections, HttpClients) can't executed on UI thread. So, we are using StrictMode.ThreadPolicy. We will get the NetworkOnMainThreadException on done.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Http Request:
Make a HTTP request to get/read the data from the WCF Service.
Working with Lazy Adapter :
public class LazyAdapter extends BaseAdapter {
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.wcf_samplelist, null);
TextView country = (TextView)vi.findViewById(R.id.country);
HashMap<String, String> Clist = new HashMap<String, String>();
Clist = data.get(position);
country.setText(Clist.get(WcfServiceActivity.KEY_CountryId)+". "+Clist.get(WcfServiceActivity.KEY_CountryName));
return vi;
}
}
Full Code:
I have created two layouts named ''wcf_sample'' and ''wcf_samplelist''. First one is main layout view and another is inflate. Follow the code below.
wcf_sample.xml:
wcf_samplelist.xml:
WcfServiceActivity:
package com.prakash_WCfDataUsage;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class WcfServiceActivity extends Activity {
static final String KEY_CountryId = "CountryID";
static final String KEY_CountryName = "CountryName";
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ListView list;
LazyAdapter adapter;
private static LayoutInflater inflater=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wcf_sample);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
ArrayList<HashMap<String, String>> CountriesList = new ArrayList<HashMap<String, String>>();
String SURL= "http://tejaprakash.com/restservice/Service.svc/GetCountries";
InputStream in = null;
String serviceResult = "";
//Assign your URL here
URL url = new URL(SURL);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
//Read the response
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while (true)
{
read = bis.read(buffer);
if (read == -1)
{
break;
}
baf.append(buffer, 0, read);
}
//Get your result here.
serviceResult = new String(baf.toByteArray());
Log.v("serviceResult", serviceResult);
//Making list.
JSONArray array = new JSONArray(serviceResult.trim());
for (int i = 0; i < array.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object = (JSONObject) array.get(i);
map.put(KEY_CountryId,object.getString("CountryID"));
map.put(KEY_CountryName, object.getString("CountryName"));
CountriesList.add(map);
}
list=(ListView)findViewById(R.id.listview);
adapter=new LazyAdapter(WcfServiceActivity.this, CountriesList);
list.setAdapter(adapter); //Setting data to Adapter.
}
catch(Exception e){ }
}
public class LazyAdapter extends BaseAdapter {
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.wcf_samplelist, null);
TextView country = (TextView)vi.findViewById(R.id.country);
HashMap<String, String> Clist = new HashMap<String, String>();
Clist = data.get(position);
country.setText(Clist.get(WcfServiceActivity.KEY_CountryId)+". "+Clist.get(WcfServiceActivity.KEY_CountryName));
return vi;
}
}
Result screen:
POST Method:
The HTTP POST is mostly used for creation of new resource. It simply submits data into specified resource.
We will post the data to server using HTTP POST in android.
Sample Data Post Format:
This is the sample format that we have to post/submit the data. And we are using below URL and format.
Code:
We have to use HTTP POST method for creation of a new resource. Here, i am creating one JSON object and passing it in Post method.
On successful, you will get the response "true". Otherwise ''false''. The PUT and DELETE requests will be almost same as like POST and GET respectively.
Enjoy coding!!!
GET Method:
The HTTP GET method is used to retrieve/read a representation of a resource.
Sample Data Format:
The sample JSON data is below.
[{"CountryID":1,"CountryName":"Andorra"},{"CountryID":2,"CountryName":"United Arab Emirates"},{"CountryID":3,"CountryName":"Afghanistan"},{"CountryID":4,"CountryName":"Antigua and Barbuda"},{"CountryID":5,"CountryName":"Anguilla"},{"CountryID":6,"CountryName":"Albania"},{"CountryID":7,"CountryName":"Armenia"},{"CountryID":8,"CountryName":"Netherlands Antilles"},{"CountryID":9,"CountryName":"Angola"},{"CountryID":10,"CountryName":"Antarctica"},{"CountryID":11,"CountryName":"Argentina"},{"CountryID":12,"CountryName":"American Samoa"},{"CountryID":13,"CountryName":"Austria"},{"CountryID":14,"CountryName":"Australia"},{"CountryID":15,"CountryName":"Aruba"},{"CountryID":16,"CountryName":"Azerbaijan"},{"CountryID":17,"CountryName":"Bosnia and Herzegovina"},{"CountryID":18,"CountryName":"Barbados"},{"CountryID":19,"CountryName":"Bangladesh"},{"CountryID":20,"CountryName":"Belgium"}]
Code:
Now, read the data from server with simple HTTP Request and display the results with the help of Lazy Adapter.
We have to use StrictMode.ThreadPolicy method here. Because, the network operations (HTTPUrlConnections, HttpClients) can't executed on UI thread. So, we are using StrictMode.ThreadPolicy. We will get the NetworkOnMainThreadException on done.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Http Request:
Make a HTTP request to get/read the data from the WCF Service.
try{
ArrayList<HashMap<String, String>> CountriesList = new ArrayList<HashMap<String, String>>();
String SURL= "http://tejaprakash.com/restservice/Service.svc/GetCountries";
InputStream in = null;
String serviceResult = "";
//Assign your URL here
URL url = new URL(SURL);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
//Read the response
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while (true)
{
read = bis.read(buffer);
if (read == -1)
{
break;
}
baf.append(buffer, 0, read);
}
//Get your result here.
serviceResult = new String(baf.toByteArray());
Log.v("serviceResult", serviceResult);
//Making list.
JSONArray array = new JSONArray(serviceResult.trim());
for (int i = 0; i < array.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object = (JSONObject) array.get(i);
map.put(KEY_CountryId,object.getString("CountryID"));
map.put(KEY_CountryName, object.getString("CountryName"));
CountriesList.add(map);
}
list=(ListView)findViewById(R.id.listview);
adapter=new LazyAdapter(WcfServiceActivity.this, CountriesList);
list.setAdapter(adapter); //Setting data to Adapter.
}
catch(Exception e){ }
ArrayList<HashMap<String, String>> CountriesList = new ArrayList<HashMap<String, String>>();
String SURL= "http://tejaprakash.com/restservice/Service.svc/GetCountries";
InputStream in = null;
String serviceResult = "";
//Assign your URL here
URL url = new URL(SURL);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
//Read the response
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while (true)
{
read = bis.read(buffer);
if (read == -1)
{
break;
}
baf.append(buffer, 0, read);
}
//Get your result here.
serviceResult = new String(baf.toByteArray());
Log.v("serviceResult", serviceResult);
//Making list.
JSONArray array = new JSONArray(serviceResult.trim());
for (int i = 0; i < array.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object = (JSONObject) array.get(i);
map.put(KEY_CountryId,object.getString("CountryID"));
map.put(KEY_CountryName, object.getString("CountryName"));
CountriesList.add(map);
}
list=(ListView)findViewById(R.id.listview);
adapter=new LazyAdapter(WcfServiceActivity.this, CountriesList);
list.setAdapter(adapter); //Setting data to Adapter.
}
catch(Exception e){ }
Working with Lazy Adapter :
public class LazyAdapter extends BaseAdapter {
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.wcf_samplelist, null);
TextView country = (TextView)vi.findViewById(R.id.country);
HashMap<String, String> Clist = new HashMap<String, String>();
Clist = data.get(position);
country.setText(Clist.get(WcfServiceActivity.KEY_CountryId)+". "+Clist.get(WcfServiceActivity.KEY_CountryName));
return vi;
}
}
Full Code:
I have created two layouts named ''wcf_sample'' and ''wcf_samplelist''. First one is main layout view and another is inflate. Follow the code below.
wcf_sample.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WCF Sample data"
android:textSize="25sp"/>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:padding="20dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WCF Sample data"
android:textSize="25sp"/>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:padding="20dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
wcf_samplelist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NA"
android:id="@+id/country"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NA"
android:id="@+id/country"
android:textStyle="bold"/>
</LinearLayout>
WcfServiceActivity:
package com.prakash_WCfDataUsage;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class WcfServiceActivity extends Activity {
static final String KEY_CountryId = "CountryID";
static final String KEY_CountryName = "CountryName";
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ListView list;
LazyAdapter adapter;
private static LayoutInflater inflater=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wcf_sample);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
ArrayList<HashMap<String, String>> CountriesList = new ArrayList<HashMap<String, String>>();
String SURL= "http://tejaprakash.com/restservice/Service.svc/GetCountries";
InputStream in = null;
String serviceResult = "";
//Assign your URL here
URL url = new URL(SURL);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
//Read the response
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while (true)
{
read = bis.read(buffer);
if (read == -1)
{
break;
}
baf.append(buffer, 0, read);
}
//Get your result here.
serviceResult = new String(baf.toByteArray());
Log.v("serviceResult", serviceResult);
//Making list.
JSONArray array = new JSONArray(serviceResult.trim());
for (int i = 0; i < array.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject object = (JSONObject) array.get(i);
map.put(KEY_CountryId,object.getString("CountryID"));
map.put(KEY_CountryName, object.getString("CountryName"));
CountriesList.add(map);
}
list=(ListView)findViewById(R.id.listview);
adapter=new LazyAdapter(WcfServiceActivity.this, CountriesList);
list.setAdapter(adapter); //Setting data to Adapter.
}
catch(Exception e){ }
}
public class LazyAdapter extends BaseAdapter {
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, final View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.wcf_samplelist, null);
TextView country = (TextView)vi.findViewById(R.id.country);
HashMap<String, String> Clist = new HashMap<String, String>();
Clist = data.get(position);
country.setText(Clist.get(WcfServiceActivity.KEY_CountryId)+". "+Clist.get(WcfServiceActivity.KEY_CountryName));
return vi;
}
}
Result screen:
POST Method:
The HTTP POST is mostly used for creation of new resource. It simply submits data into specified resource.
We will post the data to server using HTTP POST in android.
Sample Data Post Format:
This is the sample format that we have to post/submit the data. And we are using below URL and format.
Code:
We have to use HTTP POST method for creation of a new resource. Here, i am creating one JSON object and passing it in Post method.
try{
//JSON Object created
String json;
JSONObject jobj = new JSONObject();
//adding data to object
// jobj.put("Address", address.getText().toString()); //assign your TextBox text directly!!
jobj.put("Address", "Nncl Colony");
jobj.put("Address2", "");
jobj.put("City", "Hyderabad");
jobj.put("CountryID", 45);
jobj.put("Email","info@tejaprakash,com");
jobj.put("FirstName", "teja");
jobj.put("LastName", "Prakash");
jobj.put("Phone", ""NA");
jobj.put("StateID", 2);
jobj.put("UserID", 1234);
jobj.put("Zip", "500001");
json = jobj.toString();
Log.v("json",json.toString());
StringEntity input = new StringEntity(jobj.toString(), HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient();
//Add your URL here.
HttpPost httppost = new HttpPost("http://tejaprakash.com/WcfRest_service/Service.svc/PostUserProfile?");
//Pass your json object
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",json ));
httppost.setEntity(input);
//Set the header content here.
httppost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
HttpResponse response = httpclient.execute(httppost);
//Read the Response
BufferedReader reader = new BufferedReader(new
InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;)
{
builder.append(line).append("\n");
}
//Get the response!!
String responseString= builder.toString();
Log.v("response",responseString.toString());
if(responseString.equals(true))
{
Toast.makeText(getApplicationContext(), "Profile Created Successfully ", 300).show();
}
else
{
//do something!!!!
}
}
catch(Exception e){ }
//JSON Object created
String json;
JSONObject jobj = new JSONObject();
//adding data to object
// jobj.put("Address", address.getText().toString()); //assign your TextBox text directly!!
jobj.put("Address", "Nncl Colony");
jobj.put("Address2", "");
jobj.put("City", "Hyderabad");
jobj.put("CountryID", 45);
jobj.put("Email","info@tejaprakash,com");
jobj.put("FirstName", "teja");
jobj.put("LastName", "Prakash");
jobj.put("Phone", ""NA");
jobj.put("StateID", 2);
jobj.put("UserID", 1234);
jobj.put("Zip", "500001");
json = jobj.toString();
Log.v("json",json.toString());
StringEntity input = new StringEntity(jobj.toString(), HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient();
//Add your URL here.
HttpPost httppost = new HttpPost("http://tejaprakash.com/WcfRest_service/Service.svc/PostUserProfile?");
//Pass your json object
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",json ));
httppost.setEntity(input);
//Set the header content here.
httppost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
HttpResponse response = httpclient.execute(httppost);
//Read the Response
BufferedReader reader = new BufferedReader(new
InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;)
{
builder.append(line).append("\n");
}
//Get the response!!
String responseString= builder.toString();
Log.v("response",responseString.toString());
if(responseString.equals(true))
{
Toast.makeText(getApplicationContext(), "Profile Created Successfully ", 300).show();
}
else
{
//do something!!!!
}
}
catch(Exception e){ }
On successful, you will get the response "true". Otherwise ''false''. The PUT and DELETE requests will be almost same as like POST and GET respectively.
Enjoy coding!!!