How do you rate this blog

Saturday, July 5, 2014

Consume WCF data service in Android


The basic need for any application is to send or receive data. So how do we make application read or write data in a mobile, the answer is Web services / WCF  / WCF REST Services / Web API.

In this post I am going use WCF data services. 

What is WCF Data Service?


    WCF data service is a component of .NET framework which helps you to expose the specific database object(s) as services over OData (Open data protocol). The

data exchange in this happens through Atom and JSON(Java Script Object Notification)

Setting up Environment:

1) Java should be installed in your machine. If you want to download Java go to the following Link
2) Eclipse should be present in the machine. This can be downloaded in the following Link
If there is any issue like
    a) Java not installed in your machine, please add the path where java is installed on your machine to the environment variable- PATH
    b) If you have an error saying jvm.dll not found, then please check the version of eclipse that you have and then the version of java that you have installed on the system. Given below are the combinations in which eclipse will work
    32 bit OS can have 32 bit eclipse and 32 bit java (pretty straight forward)
    64 bit OS can have 32 bit eclipse and 32 bit java only
    64 bit OS can have 64 bit eclipse and 64 bit java only
3) There are 2 ways to consume WCF data services
    a) OData4j
    b) restlet
   In this post I am going to use Odata4j. This can be downloaded through the Link
Now that we have the environment set up, lets get on with the app.

What should the app do?

1) The app should be able to connect to the WCF data service
2) Ability to access a table / entity which has been exposed over the service
3) Display it in the list view.


Now lets start off with the app by creating a new android app project in eclipse. Once created import the Odata4j jar file "odata4j-0.7.0-clientbundle.jar" which will

be present in the bundles folder of Odata4j download. To import you need to right click on the project > properties > libraries > Add external jar and select the file

mentioned above. Once done go to Order and Export tab and check the library file.

Step 1 - Android Manifest File: 
This application needs access to internet so go ahead and the following code to the android manifest file
    <uses-permission android:name="android.permission.INTERNET" />

Step 2 - Creation of Layout:

This application needs the following elements in the layout:
1) Button to call the service
2) List view to display the elements we want to display on the app

The layout will look like the code below:

<LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <Button
 android:id="@+id/callbtn"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Connect to WCF" />

 <ListView
 android:id="@+id/wcflistview"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>

</LinearLayout>


Step 3 - Accessing the web service:

We need a wcf data service from which we will access an entity, we have a service called as http://services.odata.org/Northwind/Northwind.svc/. To check what are the

entities exposed in the service use the following link http://services.odata.org/Northwind/Northwind.svc/$metadata. In this post I will use Categories. To see what

data is present in this entity use the uri http://services.odata.org/Northwind/Northwind.svc/Categories

The code for connecting is given below along with the comment as to why is it used

package com.service.wcfexample;

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

import org.odata4j.consumer.ODataConsumer;
import org.odata4j.core.OEntity;
import org.odata4j.jersey.consumer.ODataJerseyConsumer;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Wcfserv extends Activity {
Button callbtn;
ListView wcflist;
ArrayList cat;
ArrayAdapter cat_adpt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wcfserv);
        callbtn=(Button) findViewById(R.id.callbtn);
        wcflist=(ListView) findViewById(R.id.wcflistview);
        cat=new ArrayList();
       
        callbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            // TODO Auto- generated method stub
            new wcfService().execute();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.wcfserv, menu);
        return true;
    }

    public class wcfService extends AsyncTask<Void, Void, ArrayList<String>>{

        @Override
        protected ArrayList<String> doInBackground(Void... arg0) {
            //To call the service
            ODataConsumer con = ODataJerseyConsumer.create("http://services.odata.org/Northwind/Northwind.svc");
            //List which will hold a particular entity from the consumer
            List<OEntity> myEntity = con.getEntities("Categories").execute().toList();
            //To add the elements of myEntity into a arraylist
            if (myEntity.size() > 0) {
                for (OEntity entity : myEntity) {
                    cat.add(entity.getProperty("CategoryID").getValue().toString()
                    + " - "
                    + entity.getProperty("CategoryName").getValue()
                    .toString());
                    }
                }
            return cat;
            }

            @Override
            protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            //displaying the result
            cat_adpt = new ArrayAdapter<String>(Wcfserv.this,
            android.R.layout.simple_list_item_1, result);
            wcflist.setAdapter(cat_adpt);
           
        }
       
       
       
    }
   
   
}

Step 4- Run the application:
Now run the application and the screen will be as shown in the snapshot below:




Now Click on connect to WCF the output will as shown below:







No comments:

Post a Comment