I have 3 classes: MainActivity, homePage and createPage; and a list List<Recipe> recipeList = new ArrayList<>() in MainActivity.
The user enters the homePage from the MainActivity. From homePage, the user can enter createPage and create a new recipe. This new recipe is intended to be passed back to MainActivity.
I've searched online and came across parcels. But when I tried, I get a NullPointerException.
Code for createPage where the list is passed on
ArrayList<Recipe> rList = new ArrayList<>();
Recipe r = new Recipe(...);
rList.add(r)
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
i.putExtras(b);
i.setClass(createPage.this, homePage.class);
startActivity(i);
Code for homePage where the list is received.
Is there something wrong with the getIntent()? Because when moving from MainActivity to homePage, it doesn't receive a bundle. Is this causing the error?
Intent intent = getIntent();
Bundle b = this.getIntent().getExtras();
if (b != null) {
Recipe r = b.getParcelable("recipe");
recipeList.add(r);
}
Code for Recipe class
public class Recipe implements Parcelable {
private String name;
private String description;
private String ingredients;
private int duration;
private String steps;
private int thumbnail;
protected Recipe(Parcel in) {
name = in.readString();
description = in.readString();
ingredients = in.readString();
duration = in.readInt();
steps = in.readString();
thumbnail = in.readInt();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getSteps() { return steps; }
public void setSteps(String steps) { this.steps = steps; }
public int getThumbnail() { return thumbnail; }
public Recipe() {}
public Recipe(String name, int duration, String ingredients, String description, String steps, int thumbnail) {
this.name = name;
this.description = description;
this.ingredients = ingredients;
this.duration = duration;
this.steps = steps;
this.thumbnail = thumbnail;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(description);
parcel.writeString(ingredients);
parcel.writeInt(duration);
parcel.writeString(steps);
parcel.writeInt(thumbnail);
}
}
you are writing into Parcelable whole array under "recipe" key
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
but on onther side you are looking not for list but for single Recipe item under same key
Recipe r = b.getParcelable("recipe");
you should use getParcelableArrayList or if you have only one Recipe for passing to another Activity just use putParcelable (not list)
Alternatively you can use serializable, that will be less complex.
For reference : https://stackoverflow.com/a/2736612/9502601
Eventhough parcellables are more faster but if you want a less complex solution then you can go for it.
For Comparison between Serializable and Parcelable.
https://stackoverflow.com/a/23647471/9502601
You can use this gson Lib for this
implementation 'com.google.code.gson:gson:2.8.9'
Send Data with Intent
Recipe r = new Recipe(...);
String recipeString = new Gson().toJson(r);
intent.putExtra("recipe",recipeString);
// For ArrayList
ArrayList<Recipe> recipeList = new ArrayList<>();
String recipeString = new Gson().toJson(recipeList);
intent.putExtra("recipeList",recipeString);
Receive Data From Intent
Recipe r = new Gson().fromJson(intent.getStringExtra("recipe"), Recipe.class);
// For Array List
Type listType = new TypeToken<ArrayList<Recipe>>(){}.getType();
ArrayList<Recipe> recipeList = new Gson().fromJson(intent.getStringExtra("recipeList"),listType);
Related
java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name = com.luzian.recipeapp.Recipe)
I've already searched for answers for this problem but they all seem to be fixed by letting both classes implement from Serializable - which I'm doing - without success.
My two Classes Recipe and Ingredient:
public class Recipe implements Serializable
{
private String name;
private String time;
private String instructions;
private ArrayList<Ingredient> ingredients;
public Recipe(String name, String time, String instructions, ArrayList<Ingredient> ingredients)
{
this.name = name;
this.time = time;
this.instructions = instructions;
this.ingredients = ingredients;
}
}
public class Ingredient implements Serializable
{
private String value;
private String unit;
private String name;
public Ingredient(String value, String unit, String name)
{
this.value = value;
this.unit = unit;
this.name = name;
}
}
Starting new Activity:
Intent intent = new Intent(context, RecipeDisplayActivity.class);
intent.putExtra("recipe", recipes.get(position)); // recipes.get(position) returns a Recipe object
context.startActivity(intent);
I changed the Serializable to Parcelable and overwrote to required methods - Now it works!
Thanks #Swayangjit
public class Recipe implements Parcelable
{
private String name;
private String time;
private String instructions;
private ArrayList<Ingredient> ingredients;
public Recipe(String name, String time, String instructions, ArrayList<Ingredient> ingredients)
{
this.name = name;
this.time = time;
this.instructions = instructions;
this.ingredients = ingredients;
}
protected Recipe(Parcel in)
{
name = in.readString();
time = in.readString();
instructions = in.readString();
ingredients = in.readArrayList(Ingredient.class.getClassLoader());
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>()
{
#Override
public Recipe createFromParcel(Parcel in)
{
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size)
{
return new Recipe[size];
}
};
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(name);
dest.writeString(time);
dest.writeString(instructions);
dest.writeList(ingredients);
}
}
public class Ingredient implements Parcelable
{
private String value;
private String unit;
private String name;
public Ingredient(String value, String unit, String name)
{
this.value = value;
this.unit = unit;
this.name = name;
}
protected Ingredient(Parcel in)
{
value = in.readString();
unit = in.readString();
name = in.readString();
}
public static final Creator<Ingredient> CREATOR = new Creator<Ingredient>()
{
#Override
public Ingredient createFromParcel(Parcel in)
{
return new Ingredient(in);
}
#Override
public Ingredient[] newArray(int size)
{
return new Ingredient[size];
}
};
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(value);
dest.writeString(unit);
dest.writeString(name);
}
}
I am trying to send and receive a parceled array object within another parceled object through bundles.
Always, Having issues with Array lengths
CODE : PARCELED ARRAY OBJECTS Author.java
public class Author implements Parcelable {
public String firstName;
public String middleInitial;
public String lastName;
public Author() {
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(this.firstName);
out.writeString(this.middleInitial);
out.writeString(this.lastName);
}
private Author(Parcel in) {
this.firstName = in.readString();
this.middleInitial = in.readString();
this.lastName = in.readString();
}
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<Author> CREATOR = new Parcelable.Creator<Author>() {
#Override
public Author createFromParcel(Parcel in) {
return new Author(in);
}
#Override
public Author[] newArray(int size) {
return new Author[size];
}
};
public String toString() {
StringBuffer sb = new StringBuffer();
if (firstName != null && !"".equals(firstName)) {
sb.append(firstName);
sb.append(' ');
}
if (middleInitial != null && !"".equals(middleInitial)) {
sb.append(middleInitial);
sb.append(' ');
}
if (lastName != null && !"".equals(lastName)) {
sb.append(lastName);
}
return sb.toString();
}
}
CODE : PARCELED BOOK OBJECT Book.java
public class Book implements Parcelable {
public int id;
public String title;
public Author[] authors;
public String isbn;
public String price;
private Book(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
in.readTypedArray(authors, Author.CREATOR);
this.isbn = in.readString();
this.price = in.readString();
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(this.id);
out.writeString(this.title);
out.writeArray(this.authors);
out.writeString(this.isbn);
out.writeString(this.price);
}
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
#Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
#Override
public Book[] newArray(int size) {
return new Book[size];
}
};
public Book(int id, String title, Author[] author, String isbn, String price) {
this.id = id;
this.title = title;
this.authors = author;
this.isbn = isbn;
this.price = price;
}
}
Call and Create objects :
Book new_book = new Book(1, title, authors.parseAuthors(author), isbn, "35$");
Intent i = new Intent(this, BookActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("key", new_book);
i.putExtras(bundle);
startActivity(i);
Remote Activity "BOOK ACTIVITY.CLASS"
Bundle bundle = getIntent().getExtras();
Book book = bundle.getParcelable("key");
Any ideas, how can i fix this issue.? NESTED PARCELED WITHIN BUNDLES. Also, I am sure if i am using the right way to read array in parcelable on author object.
Thanks,
Try using Parcel.createTypedArray(ClassLoader...) instead. From what I'm seeing, you're using readTypedArray, but not initializing the destination array before trying to read into it. In order to do it that way, you'd need to pass the current length of the array through the Parcel, and initialize the array at the correct size before reading into it.
In Activity A, I pass array using this code
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
Intent i=new Intent(getApplication(),B.class);
i.putExtra("results", results);
startActivity(i);
In Activity B, receive results
ArrayList result;
result = (ArrayList<SearchResults>)getIntent().getSerializableExtra("results");
Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
SearchResult
public class SearchResults {
private String weather = "";
private String date = "";
private String status = "";
private String timeIn="";
private String timeOut="";
private String project="";
private String description="";
private String progress="";
public void setWeather(String weather) {
this.weather = weather;
}
public String getWeather() {
return weather;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeOut(String timeOut){
this.timeOut=timeOut;
}
public String getTimeOut()
{
return timeOut;
}
public void setProject(String project){
this.project=project;
}
public String getProject()
{
return project;
}
public void setProgress(String progress){
this.progress=progress;
}
public String getProgress()
{
return progress;
}
public void setDescription(String description){
this.description=description;
}
public String getDescription()
{
return description;
}
}
Error LogCat
Process: com.example.project.myapplication, PID: 2698
java.lang.RuntimeException: Parcel: unable to marshal value com.example.project.myapplication.bean.SearchResults#94c2757
at android.os.Parcel.writeValue(Parcel.java:1397)
at android.os.Parcel.writeList(Parcel.java:738)
at android.os.Parcel.writeValue(Parcel.java:1344)
And this line
startActivity(i);
How do I use serializable for passing bean objects and also make the bean class implements serializable ? Thanks a lot.
In the same activity, I want the results saved to database.
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WD.insertWorkDetails(result,a); //a is pass from Activtity a too
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Toast.makeText(getApplication(),"DONE",Toast.LENGTH_LONG).show();
}
});
WorkDetails
public long insertWorkDetails(ArrayList<SearchResults> listItems, long id)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for(SearchResults s:listItems) {
String Project = s.getProject();
String temp = s.getDescription();
String[] ReceiveDescription = temp.split(":");
String Progress = s.getProgress();
String[] ReceiveProgress = Progress.split(":");
String TimeIn = s.getTimeIn();
String[] ReceiveTimeIn = TimeIn.split(":");
String TimeOut = s.getTimeOut();
String[] ReceiveTimeOut = TimeOut.split(":");
values.put(MyDatabaseHelper.Project,Project);
values.put(MyDatabaseHelper.WorkDescription,ReceiveDescription[1]);
values.put(MyDatabaseHelper.Percentage,ReceiveProgress[1]);
values.put(MyDatabaseHelper.TimeIn,ReceiveTimeIn[1]);
values.put(MyDatabaseHelper.TimeOut,ReceiveTimeOut[1]);
values.put("Twd_id",id);
database.insert(MyDatabaseHelper.TABLE_WORKDETAILS, null, values);
}
database.close();
return 0 ;
}
When I check my db, no listView item is added.
java.lang.RuntimeException: Parcel: unable to marshal value
com.example.project.myapplication.bean.SearchResults#94c2757
you are using getSerializableExtra to retrieve your ArrayList. This implies that SearchResults implements Serializable which is not the case. If you want an easy fix just let SearchResults implement the Serializable interface. In the case of SearchResults serialization will work out of the box. Or you could learn about Parcelable (read more about it here) and use it instead of Serializable. If you don't need to save the objects on your permanent storage, Parcelable is way more efficient than Serializable
I'm pretty new to Android programming and I've ran into this issue.
I have an object I am trying to send into a new activity, which is an instance of this class:
public final class BusinessEntity extends com.google.api.client.json.GenericJson {
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
private Contact contact;
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
#com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
private java.lang.String imageUrl;
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
private Person owner;
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
private java.util.List<java.lang.String> tag;
/**
* The value may be {#code null}.
*/
#com.google.api.client.util.Key
private java.lang.String type;
I have tried converting it to gson and sending it in a Bundle with the Intent, and converting it back to a BusinessEntity in the new Activity The problem is I can't deserialize it in the new activity because it contains objects of an arbitrary type. I have tried parsing it as a JsonArray, but I get the exception: "IllegalStateException: This is not a JSON Array." I guess because the object is not in a collection.
There are a lot of attributes in the Person and Contact class that I would like to be able to access in the new Activity, but I would also like to avoid sending each attribute separately.
Here's what I have in the first class:
Intent i = new Intent(mActivity, DetailsActivity.class);
Bundle b = new Bundle();
Gson gson = new Gson();
String business = gson.toJson(businesses.get(position));
b.putString("business", business);
i.putExtras(b);
startActivity(i);
And here's what I have in the second class:
Bundle b = getIntent().getExtras();
String json = b.getString("business");
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
Contact contact = gson.fromJson(array.get(0), Contact.class);
Long id = gson.fromJson(array.get(1), Long.class);
String imageURL = gson.fromJson(array.get(2), String.class);
Person person = gson.fromJson(array.get(3), Person.class);
List<String> tag = gson.fromJson(array.get(4), List.class);
But like I said I get a IllegalStateException at
JsonArray array = parser.parse(json).getAsJsonArray();
What is a good way to do this where I don't have to send each attribute separately?
--------------------------------------EDIT-------------------------------------------------------
I tried Parcelable, Serializable, Gson, everything... I was getting errors each time trying to cast the object back into a BusinessEntity in the new activity.
The workaround I created is I made a new class called SimpleBusiness that consists of all the attributes of BusinessEntity, Contact, and Person, implements Parcelable, and takes a BusinessEntity as a parameter in its constructor. I create a new SimpleBusiness object from the BusinessEntity I went to send to the new activity, send it with the intent, and get it from the intent from the new activity. It's kind of a weird workaround but it works perfectly.
Here is the new Class:
/**
* BusinessEntity class made with regular objects
*/
public class SimpleBusiness implements Parcelable {
//Contact
private String address1;
private String address2;
private String city;
private long contactID;
private String country;
private double latitude;
private double longitude;
private String phones;
private String postalCode;
private String province;
//BusinessEntity
private long id;
private String imageURL;
private List<String> tag;
private String type;
//Person
private String businessName;
private String firstName;
private String lastName;
private long personId;
/**
* Default no-argument constructor
*/
public SimpleBusiness(){
}
/**
* Constructor taking BusinessEntity as a parameter
* #param businessEntity
*/
public SimpleBusiness(BusinessEntity businessEntity) {
Contact contact = businessEntity.getContact();
Person person = businessEntity.getOwner();
address1 = contact.getAddress1();
address2 = contact.getAddress2();
city = contact.getCity();
contactID = contact.getContactId();
country = contact.getCountry();
latitude = contact.getLatitude();
longitude = contact.getLongitude();
phones = contact.getPhones();
postalCode = contact.getPostalCode();
province = contact.getProvince();
//BusinessEntity
id = businessEntity.getId();
imageURL = businessEntity.getImageUrl();
tag = businessEntity.getTag();
type = businessEntity.getType();
//Person
businessName = person.getBusinessName();
firstName= person.getFirstName();
lastName= person.getLastName();
personId= person.getPersonId();
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getContactID() {
return contactID;
}
public void setContactID(long contactID) {
this.contactID = contactID;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getPhones() {
return phones;
}
public void setPhones(String phones) {
this.phones = phones;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public List<String> getTag() {
return tag;
}
public void setTag(List<String> tag) {
this.tag = tag;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.address1);
dest.writeString(this.address2);
dest.writeString(this.city);
dest.writeLong(this.contactID);
dest.writeString(this.country);
dest.writeDouble(this.latitude);
dest.writeDouble(this.longitude);
dest.writeString(this.phones);
dest.writeString(this.postalCode);
dest.writeString(this.province);
dest.writeLong(this.id);
dest.writeString(this.imageURL);
dest.writeList(this.tag);
dest.writeString(this.type);
dest.writeString(this.businessName);
dest.writeString(this.firstName);
dest.writeString(this.lastName);
dest.writeLong(this.personId);
}
private SimpleBusiness(Parcel in) {
this.address1 = in.readString();
this.address2 = in.readString();
this.city = in.readString();
this.contactID = in.readLong();
this.country = in.readString();
this.latitude = in.readDouble();
this.longitude = in.readDouble();
this.phones = in.readString();
this.postalCode = in.readString();
this.province = in.readString();
this.id = in.readLong();
this.imageURL = in.readString();
this.tag = new ArrayList<String>();
in.readList(this.tag, List.class.getClassLoader());
this.type = in.readString();
this.businessName = in.readString();
this.firstName = in.readString();
this.lastName = in.readString();
this.personId = in.readLong();
}
public static final Creator<SimpleBusiness> CREATOR = new Creator<SimpleBusiness>() {
public SimpleBusiness createFromParcel(Parcel source) {
return new SimpleBusiness(source);
}
public SimpleBusiness[] newArray(int size) {
return new SimpleBusiness[size];
}
};
}
And the implementation:
Intent i = new Intent(mActivity, DetailsActivity.class);
Bundle b = new Bundle();
BusinessEntity business = businesses.get(position);
SimpleBusiness simpleBusiness = new SimpleBusiness(business);
i.putExtra("business", simpleBusiness);
//i.putExtras(b);
startActivity(i);
And in the DetailsActivity class:
Intent i = getIntent();
Bundle b = i.getExtras();
business = (SimpleBusiness)b.get("business");
Thanks for the help guys. It probably would have taken a lot longer if I didn't have the advice you guys gave me.
--------------------------------------------Edit 2--------------------------------------------
Switched to passing a BusinessEntity object directly with an EventBus. So much easier.
http://www.stevenmarkford.com/passing-objects-between-android-activities/
Pass the object:
Intent i = new Intent(mActivity, DetailsActivity.class);
BusinessEntity business = businesses.get(position);
de.greenrobot.event.EventBus.getDefault().postSticky(business);
startActivity(i);
Retrieve the object:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.busEntity = (BusinessEntity) EventBus.getDefault().removeStickyEvent(BusinessEntity.class);
setContentView(R.layout.activity_details);
}
EventBus makes your life so much easier, see the example and links in my answer to this question: Saving information from one fragment and dialog if the user navigates to another fragment in essence, no need to do any serialization or anything, just put the object on the eventbus and grab it again anywhere in your code (in another Activity, Fragment, Service etc..)
If you are able to modify BusinessEntity, then have it implement Serializable. You may then put the business as an extra:
//To put the object as an extra
...
BusinessEntity business = businesses(get(position));
Intent intent = new Intent(mActivity, DetailsActivity.class);
intent.putExtra("business", business); // Where business is now a `Serializable`
...
//To retrieve the object (in your second class).
//TODO -- Include check to see if intent has the extra first
BusinessEntity retrievedBusiness = (BusinessEntity) intent.getSerializableExtra("business")
You should use Parcelable Objects
https://github.com/codepath/android_guides/wiki/Using-Parcelable
You can do this via Serializable interface. Just let your BusinessEntity implement Serializable, like this:
public final class BusinessEntity extends com.google.api.client.json.GenericJson implements Serializable {
//your code here
...
...
}
Then create your intent and put an extra to it:
Intent i = new Intent(mActivity, DetailsActivity.class);
i.putExtra("BusinessEntity", yourBuisnessEntityObject);
startActivity(i);
And finally in your DetailsActivity:
BusinessEntity business = (BusinessEntity) getIntent().getSerializableExtra("BusinessEntity");
Voila! You have your BusinessEntity object in DetailsActivity.
EDIT:
Back to your code, I think the problem is that you put a JsonObject extra not a JsonArray. You should do the same things that you posted firstly, but with one correction:
JsonObject object = parser.parse(json).getAsJsonObject(); and then parse it as JsonObject by keys.
As a follow on from my last question: Passing Arraylist between activities? Using Parcelable
I'm now attempting to pass my ArrayList via Parcelable. However, when it's gotten from the other activity it returns null. I can't seem to figure out why. I've got the following...
ResultsList.java
public class ResultsList extends ArrayList<SearchList> implements Parcelable {
/**
*
*/
private static final long serialVersionUID = -78190146280643L;
public ResultsList(){
}
public ResultsList(Parcel in){
readFromParcel(in);
}
#SuppressWarnings({ "rawtypes" })
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public ResultsList createFromParcel(Parcel in) {
return new ResultsList(in);
}
public Object[] newArray(int arg0) {
return null;
}
};
private void readFromParcel(Parcel in) {
this.clear();
//First we have to read the list size
int size = in.readInt();
//Reading remember that we wrote first the Name and later the Phone Number.
//Order is fundamental
for (int i = 0; i < size; i++) {
String title = in.readString();
String Des = in.readString();
String message = in.readString();
SearchList c = new SearchList(title,Des,link);
this.add(c);
}
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
int size = this.size();
//We have to write the list size, we need him recreating the list
dest.writeInt(size);
//We decided arbitrarily to write first the Name and later the Phone Number.
for (int i = 0; i < size; i++) {
SearchList c = this.get(i);
dest.writeString(c.gettitle());
dest.writeString(c.getDescription());
dest.writeString(c.getmessage());
}
}
}
SearchList.java
public class SearchList {
private String title;
private String description;
private String message;
public SearchList(String name, String phone, String mail) {
super();
this.title = name;
this.description = phone;
this.message = mail;
}
public String gettitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getmessage() {
return message;
}
public void setmessage(String link) {
this.message = message;
}
}
listOfResults is declared as ResultsList listOfResults = new ResultsList(); and filled earlier in the code It's then sent with...
Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
startActivityForResult(intent,0);
Receiving...
Bundle extras = getIntent().getExtras();
ResultsList results = extras.getParcelable("results");
I'd like to point out I'm testing this null thing by checking the size() of the Arraylist going into the Bundle and then it coming out. It goes in fine and comes out null.
Didn't attach bundle to intent! (doh!) was pointed out by a kind gent on IRC! #android-dev