I have a Parcelable Contact Objects. I need to place them in ArrayList and broadcast it to the Activity. Getting error while reading the ArrayList in broadcast listener. I tried alot to resolve this issue. But could not find any solution to fix it.
Error:
java.lang.RuntimeException: Error receiving broadcast Intent { act=ip. flg=0x10 (has extras) } in io.HomeActivity$1#20d66f72
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.RuntimeException: Parcel android.os.Parcel#13cda10b: Unmarshalling unknown type code 7274601 at offset 352
at android.os.Parcel.readValue(Parcel.java:2228)
at android.os.Parcel.readListInternal(Parcel.java:2526)
at android.os.Parcel.readArrayList(Parcel.java:1842)
at android.os.Parcel.readValue(Parcel.java:2173)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2485)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getParcelableArrayList(Bundle.java:799)
at android.content.Intent.getParcelableArrayListExtra(Intent.java:5126)
at io.HomeActivity$1.onReceive(HomeActivity.java:149)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
Contact
public class Contact implements Parcelable{
private String id;
private String lookupKey;
private String dispName;
private String email;
private String mobileNo;
private Bitmap photoThumbnail;
private String statusMsg;
private int isRapo;
public Contact(){}
public Contact(String id, String lookupKey, String dispName, String email, String mobileNo, Bitmap photoThumbnail,String statusMsg,int isRapo) {
this.id = id;
this.lookupKey = lookupKey;
this.dispName = dispName;
this.email = email;
this.mobileNo = mobileNo;
//this.photoThumbnail = photoThumbnail;
this.statusMsg = statusMsg;
this.isRapo = isRapo;
}
protected Contact(Parcel in) {
id = in.readString();
lookupKey = in.readString();
dispName = in.readString();
email = in.readString();
mobileNo = in.readString();
//photoThumbnail = in.readParcelable(Bitmap.class.getClassLoader());
//photoThumbnail = (Bitmap)in.readValue(Bitmap.class.getClassLoader());
photoThumbnail = (Bitmap)in.readParcelable(Bitmap.class.getClassLoader());
statusMsg = in.readString();
isRapo = in.readInt();
}
public static final Creator<Contact> CREATOR = new Creator<Contact>() {
#Override
public Contact createFromParcel(Parcel in) {
return new Contact(in);
}
#Override
public Contact[] newArray(int size) {
return new Contact[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLookupKey() {
return lookupKey;
}
public void setLookupKey(String lookupKey) {
this.lookupKey = lookupKey;
}
public String getDispName() {
return dispName;
}
public void setDispName(String dispName) {
this.dispName = dispName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public Bitmap getPhotoThumbnail() {
return photoThumbnail;
}
public void setPhotoThumbnail(Bitmap photoThumbnail) {
this.photoThumbnail = photoThumbnail;
}
public String getStatusMsg() {
return statusMsg;
}
public void setStatusMsg(String statusMsg) {
this.statusMsg = statusMsg;
}
public int getIsRapo() {
return isRapo;
}
public void setIsRapo(int isRapo) {
this.isRapo = isRapo;
}
#Override
public String toString() {
return dispName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(lookupKey);
dest.writeString(dispName);
dest.writeString(email);
dest.writeString(mobileNo);
//dest.writeParcelable();
/*if(photoThumbnail != null) {
photoThumbnail.writeToParcel(dest, 5);
}*/
if(photoThumbnail != null){
dest.writeParcelable(photoThumbnail,flags);
}
dest.writeString(statusMsg);
dest.writeInt(isRapo);
}
}
Service
contactResIntent.putParcelableArrayListExtra("clist", contactList);
Broadcast Listener
private BroadcastReceiver contactsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(getApplicationContext(),"GOT Contacts response from service!!!",Toast.LENGTH_SHORT).show();
Log.d("#HomeActivity", "GOT Service response.");
/*Bundle data = intent.getExtras();
ArrayList<Parcelable> clist = data.getParcelableArrayList("clist");*/
ArrayList<Contact> clist = intent.getParcelableArrayListExtra("clist");
if(clist != null){
String s = clist.get(0).getClass().toString();
Log.d("#HomeActivity","CONTACTS LIST :"+s+"##"+String.valueOf(clist.size()));
}
First of all you should avoid putting a bitmap into a Parcel. It usually uses a large amount of memory and I've experienced some TransactionTooLargeException when transferring large parcelables (a limitation of 1Mb). Instead you could write just a String or an identifier that represents that thumbnail and load it again if needed.
That being said, you can try the following (check for null).
Change the constructor:
protected Contact(Parcel in) {
id = in.readString();
lookupKey = in.readString();
dispName = in.readString();
email = in.readString();
mobileNo = in.readString();
if (in.readByte() == 1) {
photoThumbnail = (Bitmap) in.readParcelable(Bitmap.class.getClassLoader());
}
statusMsg = in.readString();
isRapo = in.readInt();
}
Change the writeToParcel
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(lookupKey);
dest.writeString(dispName);
dest.writeString(email);
dest.writeString(mobileNo);
if (photoThumbnail != null){
dest.writeByte((byte) 1);
dest.writeParcelable(photoThumbnail,flags);
} else {
dest.writeByte((byte) 0);
}
dest.writeString(statusMsg);
dest.writeInt(isRapo);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Getting Error
FATAL EXCEPTION: main
Process: com.example.wuntu.tv_bucket, PID: 3895
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at com.example.wuntu.tv_bucket.Models.Cast.writeToParcel(Cast.java:136)
at android.os.Parcel.writeParcelable(Parcel.java:1437)
at android.os.Parcel.writeValue(Parcel.java:1343)
at android.os.Parcel.writeList(Parcel.java:759)
at android.os.Parcel.writeValue(Parcel.java:1365)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:686)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1330)
at android.os.Bundle.writeToParcel(Bundle.java:1079)
at android.os.Parcel.writeBundle(Parcel.java:711)
at android.content.Intent.writeToParcel(Intent.java:8790)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3112)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1541)
at android.app.Activity.startActivityForResult(Activity.java:4284)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4231)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4568)
at android.app.Activity.startActivity(Activity.java:4536)
at com.example.wuntu.tv_bucket.Adapters.CastDetailAdapter$1.onClick(CastDetailAdapter.java:124)
at android.view.View.performClick(View.java:5698)
at android.widget.TextView.performClick(TextView.java:10908)
at android.view.View$PerformClick.run(View.java:22557)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7231)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Getting error in sending arraylist of object from adapter to other activity. I wanna send my arraylist from onBindViewHolder method of Adapter to another activity but its is showing null exception error on the Cast Class in writetoParcel Method. How to send arraylist properly?
Cast Class
public class Cast implements Parcelable {
#SerializedName("cast_id")
#Expose
private Integer castId;
#SerializedName("character")
#Expose
private String character;
#SerializedName("credit_id")
#Expose
private String creditId;
#SerializedName("gender")
#Expose
private Integer gender;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("order")
#Expose
private Integer order;
#SerializedName("profile_path")
#Expose
private String profilePath;
public Cast(){
}
protected Cast(Parcel in) {
character = in.readString();
id = in.readInt();
name = in.readString();
profilePath = in.readString();
}
public static final Creator<Cast> CREATOR = new Creator<Cast>() {
#Override
public Cast createFromParcel(Parcel in) {
return new Cast(in);
}
#Override
public Cast[] newArray(int size) {
return new Cast[size];
}
};
public Integer getCastId() {
return castId;
}
public void setCastId(Integer castId) {
this.castId = castId;
}
public String getCharacter() {
return character;
}
public void setCharacter(String character) {
this.character = character;
}
public String getCreditId() {
return creditId;
}
public void setCreditId(String creditId) {
this.creditId = creditId;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public String getProfilePath() {
return profilePath;
}
public void setProfilePath(String profilePath) {
this.profilePath = profilePath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i)
{
parcel.writeString(name);
parcel.writeString(profilePath);
parcel.writeString(character);
parcel.writeInt(id);
}
}
CastDetailAdapter Class
public class CastDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Cast> detailArrayList = new ArrayList<>() ;
private UrlConstants urlConstants = UrlConstants.getSingletonRef();
private Cast cast;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private Context context;
MovieView a;
ArrayList<Cast> FullArrayList = new ArrayList<>();
public CastDetailAdapter(MovieView movieView, ArrayList<Cast> detailArrayList,ArrayList<Cast> subCastArrayList)
{
a = movieView;
this.detailArrayList = subCastArrayList;
this.FullArrayList = detailArrayList;
}
public class MyViewHolder1 extends RecyclerView.ViewHolder
{
ImageView cast_profile_picture;
TextView cast_name,cast_character_name;
public MyViewHolder1(View view)
{
super(view);
cast_profile_picture = (ImageView) view.findViewById(R.id.thumbnail);
cast_name = (TextView) view.findViewById(R.id.title);
cast_character_name = (TextView) view.findViewById(R.id.count);
}
}
public class FooterViewHolder1 extends RecyclerView.ViewHolder
{
TextView view_more;
public FooterViewHolder1(View itemView) {
super(itemView);
view_more = (TextView) itemView.findViewById(R.id.view_more);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount() -1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
context = parent.getContext();
if (viewType == VIEW_ITEM)
{
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cast_details, parent, false);
return new MyViewHolder1(v);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_layout_movie_details, parent, false);
return new FooterViewHolder1(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if(holder instanceof MyViewHolder1)
{
cast = detailArrayList.get(position);
((MyViewHolder1)holder).cast_character_name.setText(cast.getCharacter());
((MyViewHolder1)holder).cast_name.setText(cast.getName());
String url3 = urlConstants.URL_Image + cast.getProfilePath();
Picasso.with(context)
.load(url3)
.into(((MyViewHolder1)holder).cast_profile_picture);
}
else if (holder instanceof FooterViewHolder1)
{
((FooterViewHolder1)holder).view_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent intent = new Intent(context,CastViewActivity.class);
intent.putParcelableArrayListExtra("LIST",FullArrayList);
context.startActivity(intent);
}
});
}
}
#Override
public int getItemCount() {
return this.detailArrayList.size();
}
}
In your writeToParcel() method, you have
parcel.writeInt(id);
Since id is Integer, this is going to auto-unbox id. If id is null, this auto-unboxing will throw a NullPointerException.
Since there is no Parcel.writeInteger() method, you're going to have to record whether or not id is null in a separate write. Something like:
if (id == null) {
dest.writeInt(0);
}
else {
dest.writeInt(1);
dest.writeInt(id);
}
And to read it back out:
int hasId = in.readInt();
if (hasId == 1) {
id = in.readInt();
}
else {
id = null;
}
The order in which you read the values from the parcel has to be the same as the order it was written to it.
Try:
protected Cast(Parcel in) {
name = in.readString();
profilePath = in.readString();
character = in.readString();
id = in.readInt();
}
I am currently trying to pass an ArrayList of the class event into another activity as follows.events is an ArrayList of the Event class.
Intent i = new Intent(ViewEvents.this, UserFeed.class);
i.putParcelableArrayListExtra("events",events);
startActivity(i);
I am then retrieving the data as follows:
Intent i = getIntent();
ArrayList<Event> events = i.getParcelableArrayListExtra("events");
My Issue is that I get an Umarshing unknown type code 32 at offset 5788. I am not too sure how to fix this or why this is occurring. I have posted all the code for all three classes down below.Any help would be appreciated to solve this issue.
public class Event implements Parcelable {
public String tvEventName;
public String tvEventInfo;
public String tvDescription;
public String ivEventImage;
public String organizerName;
public String eventId;
public String veneuId;
public String organizerId;
public Venue venue;
public Organizer organizer;
public Event(String tvEventName, String tvEventInfo, String tvDescription, String ivEventImage, String eventId, String veneuId,Venue venue,Organizer organizer) {
this.tvEventName = tvEventName;
this.tvEventInfo = tvEventInfo;
this.tvDescription = tvDescription;
this.ivEventImage = ivEventImage;
this.eventId = eventId;
this.veneuId = veneuId;
}
public Event() {
}
protected Event(Parcel in) {
tvEventName = in.readString();
tvEventInfo = in.readString();
tvDescription = in.readString();
ivEventImage = in.readString();
organizerName = in.readString();
eventId = in.readString();
veneuId = in.readString();
organizerId = in.readString();
}
public static final Creator<Event> CREATOR = new Creator<Event>() {
#Override
public Event createFromParcel(Parcel in) {
return new Event(in);
}
#Override
public Event[] newArray(int size) {
return new Event[size];
}
};
public static Event fromJSON(JSONObject jsonObject)throws JSONException {
Event event = new Event();
//Getting the name of the event
JSONObject nameEvent = jsonObject.getJSONObject("name");
event.tvEventName = nameEvent.getString("text");
//Getting the description for the event Time and location only
JSONObject eventInfo = jsonObject.getJSONObject("start");
event.tvEventInfo = eventInfo.getString("utc");
SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("MM-dd hh:mm a");
event.eventId = jsonObject.getString("id");
try{
Date getDate = existingUTCFormat.parse(event.tvEventInfo);
String mydate = requiredFormat.format(getDate);
event.tvEventInfo = mydate;
}
catch(ParseException e){
e.printStackTrace();
}
//Getting the description of the event
JSONObject eventDescription = jsonObject.getJSONObject("description");
event.tvDescription = eventDescription.getString("text");
//Getting a thumbnail of the image for futer use.
try{
jsonObject.getJSONObject("logo");
JSONObject logo = jsonObject.getJSONObject("logo");
JSONObject original= logo.getJSONObject("original");
event.ivEventImage = original.getString("url");
Log.i("Ingo",event.ivEventImage);
}
catch (Exception exception){
event.ivEventImage ="#drawable/tree";
}
event.veneuId = jsonObject.getString("venue_id");
event.organizerId = jsonObject.getString("organizer_id");
return event;
}
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getTvEventName() {
return tvEventName;
}
public void setTvEventName(String tvEventName) {
this.tvEventName = tvEventName;
}
public String getTvEventInfo() {
return tvEventInfo;
}
public void setTvEventInfo(String tvEventInfo) {
this.tvEventInfo = tvEventInfo;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getTvDescription() {
return tvDescription;
}
public void setTvDescription(String tvDescription) {
this.tvDescription = tvDescription;
}
public String getIvEventImage() {
return ivEventImage;
}
public void setIvEventImage(String ivEventImage) {
this.ivEventImage = ivEventImage;
}
public String getVeneuId() {
return veneuId;
}
public void setVeneuId(String veneuId) {
this.veneuId = veneuId;
}
public String getOrganizerName() {
return organizerName;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public void setOrganizerName(String organizerName) {
this.organizerName = organizerName;
}
#Override
public int describeContents() {
return 0;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tvEventName);
dest.writeString(tvEventInfo);
dest.writeString(tvDescription);
dest.writeString(ivEventImage);
dest.writeString(organizerName);
dest.writeString(eventId);
dest.writeString(veneuId);
dest.writeString(organizerId);
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
}
}
CLASS 2
public class Venue implements Parcelable {
public String address;
public String city;
public String region;
public String postalCode;
public String country;
public String latitude;
public String longitude;
public String simpleAddress;
public Venue() {
}
public Venue(String address, String city, String region, String postalCode, String country, String latitude, String longitude, String simpleAddress) {
this.address = address;
this.city = city;
this.region = region;
this.postalCode = postalCode;
this.country = country;
this.latitude = latitude;
this.longitude = longitude;
this.simpleAddress = simpleAddress;
}
protected Venue(Parcel in) {
address = in.readString();
city = in.readString();
region = in.readString();
postalCode = in.readString();
country = in.readString();
latitude = in.readString();
longitude = in.readString();
simpleAddress = in.readString();
}
public static final Creator<Venue> CREATOR = new Creator<Venue>() {
#Override
public Venue createFromParcel(Parcel in) {
return new Venue(in);
}
#Override
public Venue[] newArray(int size) {
return new Venue[size];
}
};
public static Venue fromJSON(JSONObject jsonObject)throws JSONException {
Venue venue = new Venue();
if(jsonObject.getString("address_1") == null){
if(jsonObject.getString("address_2") == null)
venue.address = "No Location Available";
else
venue.address = jsonObject.getString("address_2");
}
else
venue.address = jsonObject.getString("address_1");
venue.city = jsonObject.getString("city");
venue.region = jsonObject.getString("region");
venue.postalCode = jsonObject.getString("postal_code");
venue.country = jsonObject.getString("country");
venue.latitude = jsonObject.getString("latitude");
venue.longitude = jsonObject.getString("longitude");
venue.simpleAddress =venue.address +","+ venue.city +","+ venue.country;
Log.i("SIMPLE", venue.simpleAddress);
return venue;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getSimpleAddress() {
return simpleAddress;
}
public void setSimpleAddress(String simpleAddress) {
this.simpleAddress = simpleAddress;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(address);
dest.writeString(city);
dest.writeString(region);
dest.writeString(postalCode);
dest.writeString(country);
dest.writeString(latitude);
dest.writeString(longitude);
dest.writeString(simpleAddress);
}
}
CLASS 3
public class Organizer implements Parcelable{
public String description;
public String organizerId;
public String numePastEvents;
public String numFutureEvents;
public String website;
public String facebookUsername;
public String twitter;
public String name;
public Organizer() {
}
protected Organizer(Parcel in) {
description = in.readString();
organizerId = in.readString();
numePastEvents = in.readString();
numFutureEvents = in.readString();
website = in.readString();
facebookUsername = in.readString();
twitter = in.readString();
name = in.readString();
}
public static final Creator<Organizer> CREATOR = new Creator<Organizer>() {
#Override
public Organizer createFromParcel(Parcel in) {
return new Organizer(in);
}
#Override
public Organizer[] newArray(int size) {
return new Organizer[size];
}
};
public static Organizer fromJson(JSONObject jsonObject){
Organizer organizer = new Organizer();
try {
organizer.description = jsonObject.getJSONObject("description").getString("text");
} catch (JSONException e) {
organizer.description ="NA";
e.printStackTrace();
}
try {
organizer.organizerId = jsonObject.getString("id");
} catch (JSONException e) {
organizer.organizerId = "NA";
e.printStackTrace();
}
try {
organizer.numePastEvents = jsonObject.getString("num_past_events");
} catch (JSONException e) {
organizer.numePastEvents = "Na";
e.printStackTrace();
}
try {
organizer.numFutureEvents = jsonObject.getString("num_future_events");
} catch (JSONException e) {
organizer.numFutureEvents = "NA";
e.printStackTrace();
}
try {
organizer.website = jsonObject.getString("website");
} catch (JSONException e) {
Log.i("Error",e.getMessage());
organizer.website = "NA";
e.printStackTrace();
}
try {
organizer.facebookUsername = jsonObject.getString("facebook");
} catch (JSONException e) {
organizer.facebookUsername = "NA";
e.printStackTrace();
}
try {
organizer.name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
organizer.twitter = jsonObject.getString("twitter");
} catch (JSONException e) {
e.printStackTrace();
}
return organizer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getNumePastEvents() {
return numePastEvents;
}
public void setNumePastEvents(String numePastEvents) {
this.numePastEvents = numePastEvents;
}
public String getNumFutureEvents() {
return numFutureEvents;
}
public void setNumFutureEvents(String numFutureEvents) {
this.numFutureEvents = numFutureEvents;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getFacebookUsername() {
return facebookUsername;
}
public void setFacebookUsername(String facebookUsername) {
this.facebookUsername = facebookUsername;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(description);
dest.writeString(organizerId);
dest.writeString(numePastEvents);
dest.writeString(numFutureEvents);
dest.writeString(website);
dest.writeString(facebookUsername);
dest.writeString(twitter);
dest.writeString(name);
}
When implementing the Parcelable interface, it is an absolute requirement that your reads and writes exactly match each other. In your case, this is your Event(Parcel) constructor and void writeToParcel().
However, your writeToParcel() implementation includes two writes that your constructor does not read.
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
You have to either remove these or add matching reads to your constructor.
venue = in.readParcelable(Venue.class.getClassLoader());
organizer = in.readParcelable(Organizer.class.getClassLoader());
What I want is to pass a list of list from one activity to another. Here is my approach.
Feeditem.java
public class FeedItem implements Parcelable {
private String id,status, image, timeStamp, url;
private ArrayList<CommentItem> commentItems;
public FeedItem() {
}
protected FeedItem(Parcel in) {
id = in.readString();
status = in.readString();
image = in.readString();
timeStamp = in.readString();
url = in.readString();
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
}
public static final Creator<FeedItem> CREATOR = new Creator<FeedItem>() {
#Override
public FeedItem createFromParcel(Parcel in) {
return new FeedItem(in);
}
#Override
public FeedItem[] newArray(int size) {
return new FeedItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ArrayList<CommentItem> getCommentItems() {
return commentItems;
}
public void setCommentItems(ArrayList<CommentItem> commentItems)
{
this.commentItems=commentItems;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(status);
dest.writeString(image);
dest.writeString(timeStamp);
dest.writeString(url);
dest.writeTypedList(commentItems);
}}
CommentItem.java
public class CommentItem implements Parcelable{
private String id,comment, from, timeStamp;
public CommentItem() {
}
protected CommentItem(Parcel in) {
id = in.readString();
comment = in.readString();
from = in.readString();
timeStamp = in.readString();
}
public static final Creator<CommentItem> CREATOR = new Creator<CommentItem>() {
#Override
public CommentItem createFromParcel(Parcel in) {
return new CommentItem(in);
}
#Override
public CommentItem[] newArray(int size) {
return new CommentItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(comment);
dest.writeString(from);
dest.writeString(timeStamp);
}}
ReceivingActivity.java
ArrayList<CommentItem> commentItems;
FeedItem feedItem;
commentItems=new ArrayList<>();
Bundle bundle=getIntent().getExtras();
feedItem=bundle.getParcelable("status");
if(feedItem.getCommentItems()!=null) { //help here
commentItems = feedItem.getCommentItems();
}
SendingActivity.java
Button getComments=(Button)convertView.findViewById(R.id.commentsbutton);
getComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(activity, CommentActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("status", item); //item is feeditem
i.putExtras(bundle);
activity.startActivity(i);
}
});
I am able to get all the attributes of the feeditem except the list which is giving me null in the receiving activity. Could someone please help me out with this. Thanks in advance.
I think the problem is that you're only reading in the list if it is already non-null:
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
If it's null, which it will be at that point, it doesn't get set. Just remove the non-null check and I think it will work.
commentItems = in.createTypedArrayList(CommentItem.CREATOR);
I am trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}
Ill first start this off saying i have seen all the other posts that deal with this and have tried all of them.
Im trying to do the same thing asked in the other posts, which is to pass the values of a ArrayList from one activity to another using Intent.
I feel I have implemented my class(es) correctly. The main class (Route_Class) i am using is below.
```
public class Route_Class implements Parcelable {
private double latitude = 0;
private double longitude = 0;
private double startingLat = 0;
private double startingLong = 0;
private String name = null;
private String routeName = null;
private String GeoPoints = null;
private String layout_width= null;
private String layout_height = null;
private String orientation = null;
private String xmlns = null;
private String id = null;
private boolean clickable = false;
private boolean enabled = false;
private String layout_width2 = null;
private String layout_height2 = null;
private String apiKey = null;
private ArrayList<GeoPoints_Class> geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
public Route_Class() {
System.out.println("crash 110");
}
public Route_Class(String name, double latitude, double longitude, double startingLat, double startingLong, String routeName, String GeoPoints, String layout_width, String layout_height, String orientation, String xmlns, String id, boolean clickable, boolean enabled, String layout_width2, String layout_height2, String apiKey, ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.layout_width2 = layout_width2;
this.latitude = latitude;
this.longitude = longitude;
this.startingLat = startingLat;
this.startingLong = startingLong;
this.routeName = routeName;
this.GeoPoints = GeoPoints;
this.layout_width = layout_width;
this.layout_height = layout_height;
this.orientation = orientation;
this.xmlns = xmlns;
this.id = id;
this.clickable = clickable;
this.enabled = enabled;
this.layout_height2 = layout_height2;
this.apiKey = apiKey;
this.geoPoints_arraylist = geoPoints_arraylist;
System.out.println("crash 16");
}
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
System.out.println("crash 17");
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 18");
dest.writeDouble(latitude);
dest.writeDouble(longitude);
dest.writeDouble(startingLat);
dest.writeDouble(startingLong);
dest.writeString(name);
dest.writeString(routeName);
dest.writeString(GeoPoints);
dest.writeString(layout_width);
dest.writeString(layout_height);
dest.writeString(orientation);
dest.writeString(xmlns);
dest.writeString(id);
dest.writeInt(clickable ? 0 : 1 );
dest.writeInt(enabled ? 0 : 1 );
dest.writeString(layout_width2);
dest.writeString(layout_height2);
dest.writeString(apiKey);
dest.writeTypedList(geoPoints_arraylist);
// dest.writeList((List<GeoPoints_Class>)geoPoints_arraylist);
// dest.writeParcelable((Parcelable) geoPoints_arraylist, 0);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Route_Class> CREATOR = new Parcelable.Creator<Route_Class>() {
public Route_Class createFromParcel(Parcel in) {
System.out.println("crash 20");
return new Route_Class(in);
}
public Route_Class[] newArray(int size) {
System.out.println("crash 21");
return new Route_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Route_Class(Parcel in) {
layout_width2 = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
startingLat = in.readDouble();
startingLong = in.readDouble();
name = in.readString();
routeName = in.readString();
GeoPoints = in.readString();
layout_width = in.readString();
layout_height = in.readString();
orientation = in.readString();
xmlns = in.readString();
id = in.readString();
clickable = in.readInt() == 0;
enabled = in.readInt() == 0;
layout_height2 = in.readString();
apiKey = in.readString();
System.out.println("crash 5");
//geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
if (geoPoints_arraylist == null) {
geoPoints_arraylist = new ArrayList<GeoPoints_Class>();
}
try {
in.readTypedList(geoPoints_arraylist, GeoPoints_Class.CREATOR);
} catch (Exception e) {
System.out.println("Error " + e);
}
// in.readList(geoPoints_arraylist, com.breckbus.app.GeoPoints_Class.class.getClassLoader());
System.out.println("crash 6");
// geoPoints_arraylist = (ArrayList<GeoPoints_Class>)in.readParcelable(com.breckbus.app.Route_Class.GeoPoints_Class. class.getClassLoader());
}
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 double getstartingLat() {
return startingLat;
}
public void setstartingLat(double startingLat) {
this.startingLat = startingLat;
}
public double getstartingLong() {
return startingLong;
}
public void setstartingLong(double startingLong) {
this.startingLong = startingLong;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getrouteName() {
return routeName;
}
public void setrouteName(String routeName) {
this.routeName = routeName;
}
public String getGeoPoints() {
return GeoPoints;
}
public void setGeoPoints(String GeoPoints) {
this.GeoPoints = GeoPoints;
}
public String getLayout_width() {
return layout_width;
}
public void setLayout_width(String layout_width) {
this.layout_width = layout_width;
}
public String getLayout_height() {
return layout_height;
}
public void setLayout_height(String layout_height) {
this.layout_height = layout_height;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getOrientation() {
return orientation;
}
public void setOrientation(String orientation) {
this.orientation = orientation;
}
public String getXmlns() {
return xmlns;
}
public void setXmlns(String xmlns) {
this.xmlns = xmlns;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isClickable() {
return clickable;
}
public void setClickable(boolean clickable) {
this.clickable = clickable;
}
public String getLayout_width2() {
return layout_width2;
}
public void setLayout_width2(String layout_width2) {
this.layout_width2 = layout_width2;
}
public String getLayout_height2() {
return layout_height2;
}
public void setLayout_height2(String layout_height2) {
this.layout_height2 = layout_height2;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Route Class Details:").append("\n\n");
sb.append("latitude: ").append(getlatitude());
sb.append("\n");
sb.append("longitude: ").append(getlongitude());
sb.append("\n");
sb.append("startingLat: ").append(getstartingLat());
sb.append("\n");
sb.append("startingLong: ").append(getstartingLong());
sb.append("\n");
sb.append("name: ").append(getname());
sb.append("\n");
sb.append("routeName: ").append(getrouteName());
sb.append("\n");
sb.append("GeoPoints: ").append(getGeoPoints());
sb.append("\n");
sb.append("layout_width: ").append(getLayout_width());
sb.append("\n");
sb.append("layout_height: ").append(getLayout_height());
sb.append("\n");
sb.append("orientation: ").append(getOrientation());
sb.append("\n");
sb.append("xmlns: ").append(getXmlns());
sb.append("\n");
sb.append("id: ").append(getId());
sb.append("\n");
sb.append("clickable: ").append(isClickable());
sb.append("\n");
sb.append("enabled: ").append(isEnabled());
sb.append("\n");
sb.append("layout_width2: ").append(layout_width2);
sb.append("\n");
sb.append("layout_height2: ").append(getLayout_height2());
sb.append("\n");
sb.append("apiKey: ").append(getApiKey());
return sb.toString();
}
// public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
// return geoPoints_arraylist;
// }
public ArrayList<GeoPoints_Class> getGeoPoints_arraylist() {
return geoPoints_arraylist;
}
public void setGeoPoints_arraylist(ArrayList<GeoPoints_Class> geoPoints_arraylist) {
this.geoPoints_arraylist = geoPoints_arraylist;
}
public GeoPoints_Class getGeoPoints(int i) {
return geoPoints_arraylist.get(i);
}
public void addGeoPoint(double lat, double lon, String location) {
this.geoPoints_arraylist.add(new GeoPoints_Class(lat, lon, location));
}
}
```
Here is my second class (GeoPoints_Class) that is used in Route_Class.
```
package com.breckbus.app;
import android.os.Parcel;
import android.os.Parcelable;
class GeoPoints_Class implements Parcelable {
private double lat;
private double lon;
private String location;
public GeoPoints_Class(){
System.out.println("crash 99");
}
public GeoPoints_Class(double lat, double lon, String location){
System.out.println("crash 7");
this.lat = lat;
this.lon = lon;
this.location = location;
}
public int describeContents() {
return this.hashCode();
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel dest, int flags) {
System.out.println("crash 11");
dest.writeDouble(lat);
dest.writeDouble(lon);
dest.writeString(location);
System.out.println("crash 12");
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<GeoPoints_Class> CREATOR = new Parcelable.Creator<GeoPoints_Class>() {
public GeoPoints_Class createFromParcel(Parcel in) {
System.out.println("crash 28");
return new GeoPoints_Class(in);
}
public GeoPoints_Class[] newArray(int size) {
System.out.println("crash 29");
return new GeoPoints_Class[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private GeoPoints_Class(Parcel in) {
System.out.println("crash 13");
lat = in.readDouble();
lon = in.readDouble();
location = in.readString();
System.out.println("crash 14");
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GeoPoint Class Details:").append("\n\n");
sb.append("latitude: ").append(getLat());
sb.append("\n");
sb.append("longitude: ").append(getLon());
sb.append("\n");
sb.append("location: ").append(getLocation());
sb.append("\n");
return sb.toString();
}
}
```
Next is where I put the objects using putExtra.
```
Intent i = new Intent("com.breckbus.app.ROUTE");
// i.putParcelableArrayListExtra("route_Classes_temp", route_Classes);
i.putExtra("route_Classes_temp",route_Classes);
System.out.println("crash 1");
```
Then where i get the objects.
```
Bundle extras = getIntent().getExtras();
Intent d = getIntent();
System.out.println("crash 25");
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
System.out.println("crash 2");
// route_Classes = getIntent().getParcelableArrayListExtra("route_Classes_temp");
```
You will notice all of my manual debug statements since Eclipse doesnt work with android applications in debug mode (breakpoints and stuff). (Which if you know the solution to that, it would greatly help).
Next is the only error i get and where the manual debug statements i entered in the code stop. I dont know where it is crashing anymore.
Here is the first couple errors:
```
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.165: I/System.out(323): crash 28
10-26 00:03:50.165: I/System.out(323): crash 13
10-26 00:03:50.165: I/System.out(323): crash 14
10-26 00:03:50.185: I/System.out(323): crash 6
10-26 00:03:50.195: D/AndroidRuntime(323): Shutting down VM
10-26 00:03:50.195: W/dalvikvm(323): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-26 00:03:50.225: E/AndroidRuntime(323): FATAL EXCEPTION: main
10-26 00:03:50.225: E/AndroidRuntime(323): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.breckbus.app/com.breckbus.app.route}: java.lang.RuntimeException: Parcel android.os.Parcel#44edd958: Unmarshalling unknown type code 6553714 at offset 968
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.os.Looper.loop(Looper.java:123)
10-26 00:03:50.225: E/AndroidRuntime(323): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invokeNative(Native Method)
10-26 00:03:50.225: E/AndroidRuntime(323): at java.lang.reflect.Method.invoke(Method.java:521)
```
I hope i provided enough information. Please tell me what i am doing wrong when trying to pass the route_class ArrayList of Object type Route_Class from one activity to another using Intent. These two lines:
i.putExtra("route_Classes_temp",route_Classes);
route_Classes = d.getParcelableArrayListExtra("route_Classes_temp");
Thank you for your help, it is much appreciated.
It is true that you have provided too much information.
However, is this on the same process (i.e. your own app only?) If yes, then avoid doing that entirely. It will be too slow to parcel/unparcel these objects.
Use a singleton where you store your data and just access the singleton from each activity.