Tuesday, April 30, 2013

Android MapActivity cannot be resolved

While I was working in a Android Map based application, I came across that MapActivty couldn't be resolved. Since I was upgraded my SDK Tools & SDK Platform Tools to the very latest versions, I was unable to set the target of my app to Google API [desired version] as mentioned in many tutorials. Finnaly I was able to fix the issue by manually setting the Android Build Target of my project to Google API(Platform 3.1, API Level 12)

Eclipse -> Select the project -> Properties -> Android -> Target Name -> tick the desired Google API level

Accessing WCF Service via Android

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.

WCF Service

Entity
public class Item{

        public string Id { get; set; }

        public string Name { get; set; }

        public string Url { get; set; }

        public string CategoryId { get; set; }

        public virtual Category Category { get; set; }

        public int InStock { get; set; }

        public decimal Price { get; set; }

 }

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

            HasRequired(item => item.Category)
                .WithMany()
                .HasForeignKey(item => new { item.CategoryId });
        }   
}

Repository
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)
        {
            ItemSet.Include(item => item.Category);
            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
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<Item> GetItems(string From, string To)
{
       var itemRepo = new ItemRepo(new DataContext());
       return itemRepo.GetItems(From, To);
}

Android-Client side

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]

Mapping

public class Item {

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

public String getId() {
 return Id;
}
public void setId(String id) {
 Id = id;
}
public String getName() {
 return Name;
}
public void setName(String name) {
 Name = name;
}
public Integer getOrderQty() {
 return OrderQty;
}
public void setOrderQty(int orderQty) {
 OrderQty = orderQty;
}
public int getInStock() {
 return InStock;
}
public void setInStock(int inStock) {
 InStock = inStock;
}
public String getUrl() {
 return Url;
}
public void setUrl(String url) {
 Url = url;
}
public Double getPrice() {
 return Price;
}
public void setPrice(Double price) {
 Price = price;
}
}


WCF Service accessing method

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.