Saturday, April 5, 2014

Communicating non-primitive data objects between Android Activities

Non-primitive types such as ArrayLists can be communicated between Activities in Android using Parcelable interface.
Sample Example:
Class Definition:


package com.example.comparisonapp;

import android.os.Parcel;
import android.os.Parcelable;

public class Product implements Parcelable{
private String asin;
private String imageUrl;
private String description;
private String title;
private Double rating = 0.0;

public String getAsin() {
return asin;
}
public void setAsin(String asin) {
this.asin = asin;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}

public Product() {;}

public Product(Parcel in) {
this.asin = in.readString();
this.imageUrl = in.readString();
this.description = in.readString();
this.title = in.readString();
this.rating = in.readDouble();
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
arg0.writeString(asin);
arg0.writeString(imageUrl);
arg0.writeString(description);
arg0.writeString(title);
arg0.writeDouble(rating);
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Product createFromParcel(Parcel in) {
return new Product(in);
}
public Product[] newArray(int size) {
return new Product[size];
}
};
}


Caution:
1. The order of reading data from the Parcel in Parcel argument constructor must be the same as order of writing the data in the Parcel in the writeToParcel method.

Initializing the objects of the class and sending as intent.

products = new ArrayList<Product>();
for(int i=0;i<3;i++) {
Product product = new Product();
product.setAsin("asin " + i);
product.setTitle("Title " + i);
product.setDescription("description " + i);
product.setRating(4.5);
product.setImageUrl("imageUrl");
products.add(product);
}
intent.putExtra("products", products);
startActivity(intent);


Reading the data from the intent

Intent intent = getIntent();
ArrayList<Product> products = intent.getExtras().getParcelableArrayList("products");
for(int i=0;i<products.size();i++) {
Toast.makeText(getApplicationContext(), "Got: " + String.valueOf(products.get(i).getAsin()), Toast.LENGTH_SHORT).show();
}

No comments:

Post a Comment