Accessing WCF Service via Android (WCF, EF 4.1, SQLServer 2008 R2, Android, Gson)

Recent past as an R&D Project I was working on a prototype basis Shopping cart application (assuming that the end-users are always in a connected environment-WiFi/3G) which has no local database so that it had to interact with WCF Service for data-manipulation.

WCF Service, data handling section was developed using Entity Framework(Code First approach). There were several modules like Item, Category, Order etc. Among those I picked Item module for further explanation.

Entity Class – Item

public class Item
{
	public string Id { get; set; }

	public string Name { get; set; }

	public string Url { get; set; }

	public int InStock { get; set; }

	public decimal Price { get; set; }
}

Entity Map – ItemMap

public class ItemMap : EntityTypeConfiguration<Item>
{
	public ItemMap()
	{
		ToTable("tbl_Item");
		HasKey(item => item.Id);
	}
}

Repository – ItemRepo

public class ItemRepo
{
    protected IDbSet<Item> ItemSet;
    protected DataContext Context;

    public ItemRepo(DataContext dataContext)
    {
        Context = dataContext;
        ItemSet = dataContext.Set<Item>();
    }

    public List<Item> GetItems(string from, string to)
    {
        IEnumerable<Item> items = (from a in ItemSet
                                   select a).OrderBy(a => a.Id).Skip(Convert.ToInt32(from)).Take(Convert.ToInt32(to));

        return items.ToList();
    }
}

WCF Service Method

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Html5Service
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List<Item> GetItems(string From, string To)
    {
        var itemRepo = new ItemRepo(new DataContext());
        return itemRepo.GetItems(Convert.ToInt32(From), Convert.ToInt32(To));
    }
}

Client(Android) side implementation was as follows.

You have to access the WCF Service with a similar function like below. I have used a third party library called gson-1.7.1(not the latest one), which can be downloaded from the below link.
download google-gson

Item-Mapping [since my mapping properties had the same name with compared to the json result item list, i have not used the SerializedName annotation]

Class – Item

public class Item{

	private String Id;
	private String Name;
	private String Url;
	private int InStock;
	private Double Price;

	public String getId() {
		return Id;
	}
	public void setId(String id) {
		Id = url;
	}

	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}

	public String getUrl() {
		return Url;
	}
	public void setUrl(String url) {
		Url = url;
	}

	public int getInStock() {
		return InStock;
	}
	public void setInStock(int inStock) {
		InStock = inStock;
	}

	public Double getPrice() {
		return Price;
	}
	public void setPrice(Double price) {
		Price = price;
	}
}

WCF Service call

public List<Item> getItems(String from, String to) {

	List<Item> items = null;
	Gson gson = new Gson();

	try {

		String urlWithParam = String.format("http://app.dinotait.com/Items/HTML5Service.svc/GetItems?From=%s&To=%s",from, to);

		HttpGet request = new HttpGet(urlWithParam);

		request.setHeader("Accept", "application/json");
		request.setHeader("Content-type", "application/json");

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(request);

		HttpEntity responseEntity = response.getEntity();

		// Read response data into buffer
		char[] buffer = new char[(int) responseEntity.getContentLength()];
		InputStream stream = responseEntity.getContent();
		InputStreamReader reader = new InputStreamReader(stream);
		reader.read(buffer);
		stream.close();

		Type type = new TypeToken<List<Item>>(){}.getType();
		items = gson.fromJson(new String(buffer), type);

	} catch (Exception e) {
		e.printStackTrace();
	}

	return items;
}

Remember that you have to execute this function within an AsyncTask or similar approach since this is a network operation.