Custom Object intent Parcelable element arraylist - java

This code works but I do not pass the data contained in the arrayList.
public class Percorso implements Parcelable {
int id;
String nome;
double distanza;
int numero_commenti;
double valutazione;
ArrayList<Commento> commenti;
ArrayList<Cordinate> cordinate;
public Percorso(){
}
protected Percorso(Parcel in) {
id = in.readInt();
nome = in.readString();
distanza = in.readDouble();
numero_commenti = in.readInt();
valutazione = in.readDouble();
}
public static final Creator<Percorso> CREATOR = new Creator<Percorso>() {
#Override
public Percorso createFromParcel(Parcel in) {
return new Percorso(in);
}
#Override
public Percorso[] newArray(int size) {
return new Percorso[size];
}
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getDistanza() {
return distanza;
}
public void setDistanza(double distanza) {
this.distanza = distanza;
}
public int getNumero_commenti() {
return numero_commenti;
}
public void setNumero_commenti(int numero_commenti) {
this.numero_commenti = numero_commenti;
}
public double getValutazione() {
return valutazione;
}
public void setValutazione(double valutazione) {
this.valutazione = valutazione;
}
public ArrayList<Commento> getCommenti() {
return commenti;
}
public void setCommenti(ArrayList<Commento> commenti) {
this.commenti = commenti;
}
public ArrayList<Cordinate> getCordinate() {
return cordinate;
}
public void setCordinate(ArrayList<Cordinate> cordinate) {
this.cordinate = cordinate;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(nome);
parcel.writeDouble(distanza);
parcel.writeInt(numero_commenti);
parcel.writeDouble(valutazione);
}
}
//
public class Cordinate implements Parcelable {
double latitudine;
double longitudin;
public Cordinate(){}
protected Cordinate(Parcel in) {
latitudine = in.readDouble();
longitudin = in.readDouble();
}
public static final Creator<Cordinate> CREATOR = new Creator<Cordinate>() {
#Override
public Cordinate createFromParcel(Parcel in) {
return new Cordinate(in);
}
#Override
public Cordinate[] newArray(int size) {
return new Cordinate[size];
}
};
public double getLatitudine() {
return latitudine;
}
public void setLatitudine(double latitudine) {
this.latitudine = latitudine;
}
public double getLongitudin() {
return longitudin;
}
public void setLongitudin(double longitudin) {
this.longitudin = longitudin;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeDouble(latitudine);
parcel.writeDouble(longitudin);
}
}
INTENT
Percorso percorsoClick = listaPercorsi.get(i);
Intent intent = new Intent(getBaseContext(), PercorsoActivity.class);
intent.putExtra("percorso", percorsoClick);
startActivity(intent);
GET INTENT
percorso = getIntent().getParcelableExtra("percorso");
System.out.println(percorso.getNome());
getNome() work because is not a arrayList.
instead get getCordinate not work.
percorso.getCordinate().size() // null
I hope it was clear. I have set the Parcelable implementation on all classes.
Thank you very much for the help

ArrayList<Cordinate> cordinate; is not being parcelled. You still have to take care of write/read in/from Parcel parcel. Eg
protected Percorso(Parcel in) {
id = in.readInt();
nome = in.readString();
distanza = in.readDouble();
numero_commenti = in.readInt();
valutazione = in.readDouble();
cordinate = new ArrayList<Cordinate>();
in.readList(cordinate,Cordinate.class.getClassLoader());
}
and
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(nome);
parcel.writeDouble(distanza);
parcel.writeInt(numero_commenti);
parcel.writeDouble(valutazione);
parcel.writeList(cordinate);
}

Related

How to implement Parcelable for double ArrayList?

I got a JSON with an array of doubles and another for Strings. I am trying to create a Parcelable model class with the relevant methods. When the methods are created automaticaly, no line for the doubles' array list is created.
I looked for relevant questions and information, but, surprisingly, couldn't find any. I also added a jar file that was supposed to assist: android-parcelable-intellij-plugin.jar. Don't know what it's supposed to do and couldn't find information on how to use it.
My question is what should I write in the methods in order to get the array of doubles in a List.
The code:
public class Country implements Parcelable {
...
private List<String> timezones;
private List<Double> latlng;
protected Country(Parcel in) {
timezones = in.createStringArrayList();
this.latlng = new ArrayList<>(); // from jsonschema2pojo.org
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(timezones);
//nothing for the double array
}
public List<Double> getLatlng() {
return latlng;
}
public void setLatlng(List<Double> latlng) {
this.latlng = latlng;
}
public List<String> getTimezones() {
return timezones;
}
public void setTimezones(List<String> timezones) {
this.timezones = timezones;
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
}
...
Thanks.
Try this below, it works for me :
public class Country implements Parcelable {
private List<String> timezones;
private List<Double> latlng;
public Country(List<String> timezones, List<Double> latlng) {
this.timezones = timezones;
this.latlng = latlng;
}
protected Country(Parcel in) {
timezones = in.createStringArrayList();
double[] doubleArray = in.createDoubleArray();
latlng = new ArrayList<>();
if (doubleArray != null) {
for (double ele : doubleArray) {
latlng.add(ele);
}
}
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(timezones);
double[] doubleArray = new double[latlng == null ? 0 : latlng.size()];
for (int i=0, len=latlng.size(); i<len; i++) {
doubleArray[i] = latlng.get(i);
}
dest.writeDoubleArray(doubleArray);
}
#Override
public String toString() {
return "Country{" +
"timezones=" + timezones +
", latlng=" + latlng +
'}';
}
}

Can't get data out of method or in other activities on android app

I'm trying to store data from the user that logs into the app in a class so I can use all it's data in all activities.
I've followed a couple of guide on serializable but I can't get it to work.
This function calls the user object from my api:
public void GetGame(String UID){
String url = "https://worldapi.azurewebsites.net/api/homeracer/user/"+UID;
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("tag", "jsonresponse" + response.toString());
try {
//String name = response.getString("userName");
currentUser.setUserId(response.getInt("userId"));
currentUser.setStartLat(response.getInt("startLat"));
currentUser.setStartLong(response.getDouble("startLong"));
currentUser.setEndLat(response.getDouble("endLat"));
currentUser.setEndLong(response.getDouble("endLong"));
currentUser.setUsername(response.getString("userName"));
startLong.setText(String.valueOf(currentUser.getStartLong()));
userName.setText(currentUser.getUsername());
//Intent sendObj = new Intent(Homescreen.this, Homescreen.class);
bundle = new Bundle();
bundle.putSerializable("userInfo", currentUser);
//sendObj.putExtras(bundle);
//startActivity(sendObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.toString());
}
}
);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//mRequestQueue.add(jsonObjectRequest);
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
Now when I try to get the username or any other data from my currentuser anywhere but in the 'onResponse' method. The field is empty.
So my question: How do I set the currentUser object so that I can use all it's fields in my acitvity and send it to other activites aswell.
I've tried with sharedpreferences and it worked, but I read somewhere that's not ideal.
UserData class:
public class UserData implements Serializable {
int UserId;
double EndLat, EndLong, StartLat, StartLong;
String Username;
/*public Userdata(){
}
public Userdata(String username, double endLat, double endLong, double startLat
,double startLong, int userId){
this.Username = username;
this.UserId = userId;
this.StartLat = startLat;
this.StartLong = startLong;
this.EndLat = endLat;
this.EndLong = endLong;
}*/
public void setUserId(int _userId) {
this.UserId = _userId;
}
public int getUserId() {
return UserId;
}
public void setEndLat(double _endLat) {
this.EndLat = _endLat;
}
public double getEndLat() {
return EndLat;
}
public void setStartLat(double _startLat) {
this.StartLat = _startLat;
}
public double getStartLat() {
return StartLat;
}
public void setEndLong(double _endLong) {
this.EndLong = _endLong;
}
public double getEndLong() {
return EndLong;
}
public void setStartLong(double _startLong) {
this.StartLong = _startLong;
}
public double getStartLong() {
return StartLong;
}
public void setUsername(String username) {
this.Username = username;
}
public String getUsername() {
return Username;
}
}
In Android you can easily pass an object throughout Activities by implementing the Parcelableinterface.
The steps are:
Your class should implement the Parcelable interface.
Create an Intentthat targets the Activitythat you want to navigate and pass your object using the putExtra() method.
Retrieve your object from the new Activity.
Bellow is your UserData class implementing Parcelable. Android Studio helps you to accomplish this task pretty easily.
public class UserData implements Parcelable {
private int UserId;
private double EndLat, EndLong, StartLat, StartLong;
private String Username;
public void setUserId(int _userId) {
this.UserId = _userId;
}
public int getUserId() {
return UserId;
}
public void setEndLat(double _endLat) {
this.EndLat = _endLat;
}
public double getEndLat() {
return EndLat;
}
public void setStartLat(double _startLat) {
this.StartLat = _startLat;
}
public double getStartLat() {
return StartLat;
}
public void setEndLong(double _endLong) {
this.EndLong = _endLong;
}
public double getEndLong() {
return EndLong;
}
public void setStartLong(double _startLong) {
this.StartLong = _startLong;
}
public double getStartLong() {
return StartLong;
}
public void setUsername(String username) {
this.Username = username;
}
public String getUsername() {
return Username;
}
// Parcelable implementation bellow this line
protected UserData(Parcel in) {
UserId = in.readInt();
EndLat = in.readDouble();
EndLong = in.readDouble();
StartLat = in.readDouble();
StartLong = in.readDouble();
Username = in.readString();
}
public static final Creator<UserData> CREATOR = new Creator<UserData>() {
#Override
public UserData createFromParcel(Parcel in) {
return new UserData(in);
}
#Override
public UserData[] newArray(int size) {
return new UserData[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(UserId);
parcel.writeDouble(EndLat);
parcel.writeDouble(EndLong);
parcel.writeDouble(StartLat);
parcel.writeDouble(StartLong);
parcel.writeString(Username);
}
}
Create the Intent:
Intent intent = new Intent(context/*your activity*/, TargetActivity.class);
Now pass the object to the intent. intent.putExtra("your_key",yourObject);
Start your activity startActivity(intent).
Finally from the TargetActivityobtain the object that was passed here from the Intent.
UserData yourObject = getIntent().getParcelableExtra("your_key");
That's it!

How to pass a class with an abstract class type as parameter in parcelable android studio java

I am trying to pass this class as a parcelable in android.
public class Outfit implements Parcelable {
private List<Item> itemList;
private String mName;
private String mImageUrl;
public Outfit() {}
public Outfit(String mName, String mImageUrl) {
this.mName = mName;
this.mImageUrl = mImageUrl;
}
protected Outfit(Parcel in) {
itemList = in.createTypedArrayList(Item.CREATOR);
mName = in.readString();
mImageUrl = in.readString();
}
public static final Creator<Outfit> CREATOR = new Creator<Outfit>() {
#Override
public Outfit createFromParcel(Parcel in) {
return new Outfit(in);
}
#Override
public Outfit[] newArray(int size) {
return new Outfit[size];
}
};
public String getmName() {
return mName;
}
public String getmImageUrl() {
return mImageUrl;
}
#Override
public String toString() {
return mName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeTypedList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
}
the problem is that Item is abstract and itemList = in.creatTypedArrayList(Item.CREATOR) because Item does not have a CREATOR . Only its subclasses have this implementation.
Item.java
public abstract class Item implements Parcelable {
private String mName;
private String mColor;
private String mImageUrl;
private List<TagHolder> tags = new ArrayList<>();
private String mKey;
public Item(){
}
public Item(String mName, String mColor, String mImageUrl) {
this.mName = mName;
this.mColor = mColor;
this.mImageUrl = mImageUrl;
}
protected Item(Parcel in) {
mName = in.readString();
mColor = in.readString();
mImageUrl = in.readString();
tags = in.createTypedArrayList(TagHolder.CREATOR);
mKey = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeString(mColor);
dest.writeString(mImageUrl);
dest.writeTypedList(tags);
dest.writeString(mKey);
}
#Override
public int describeContents() {
return 0;
}
public void setmName(String mName) {
this.mName = mName;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public List<TagHolder> getTags() {
return tags;
}
public String getmColor() {
return mColor;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmColor(String mColor) {
this.mColor = mColor;
}
public String getmName() {
return mName;
}
public void setTags(List<TagHolder> tags) {
this.tags = tags;
}
#Exclude // dont need this in our firebase database
public String getKey() {
return mKey;
}
#Exclude
public void setMkey(String key) {
mKey = key;
}
public abstract String getCategory();
}
I am able to parce a List as a parcelable array when I call put extra. But when I try to do so for outfit it gives error . Is there any way to pass Outfit as a parcelable?
Do you try using another method for the list?
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
protected Outfit(Parcel in) {
in.readList(itemList, Item.class.getClassLoader());
mName = in.readString();
mImageUrl = in.readString();
}

readTypedList throws OutOfMemoryError while using Parcelable in Android

I have three models as follows :
Coordinate Model
public class Coordinate implements Parcelable{
private static final long serialVersionUID = 1L;
private double latitude,longitude;
private double x,y;
private double bearing,distance;
protected Coordinate(Parcel in) {
latitude = in.readDouble();
longitude = in.readDouble();
x = in.readDouble();
y = in.readDouble();
bearing = in.readDouble();
distance = in.readDouble();
}
public static final Creator<Coordinate> CREATOR = new Creator<Coordinate>() {
#Override
public Coordinate createFromParcel(Parcel in) {
return new Coordinate(in);
}
#Override
public Coordinate[] newArray(int size) {
return new Coordinate[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(latitude);
dest.writeDouble(longitude);
dest.writeDouble(x);
dest.writeDouble(y);
dest.writeDouble(bearing);
dest.writeDouble(distance);
}
public Coordinate(double lat,double lng,double x,double y,double distance,double bearing){
this.latitude=lat;
this.longitude=lng;
this.x=x;
this.y=y;
this.distance=distance;
this.bearing=bearing;
}
private Coordinate() {
// TODO Auto-generated constructor stub
}
public double getBearing() {
return bearing;
}
public double getDistance() {
return distance;
}
public double getLatitude() {
return latitude;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getLongitude() {
return longitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void setBearing(double bearing) {
this.bearing = bearing;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
Area Model which uses Coordinate
public class Area implements Parcelable{
private static final long serialVersionUID = 1L;
private List<Coordinate> coordinates;
private static Double R=63710000.0;
protected Area(Parcel in) {
coordinates = new ArrayList<Coordinate>();
in.readTypedList(coordinates,Coordinate.CREATOR);
}
public static final Creator<Area> CREATOR = new Creator<Area>() {
#Override
public Area createFromParcel(Parcel in) {
return new Area(in);
}
#Override
public Area[] newArray(int size) {
return new Area[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(coordinates);
}
private Area() {
}
public Area(List<Coordinate> coordinates) {
this.coordinates = coordinates;
}
public Area(LatLng origin){
coordinates=new ArrayList<Coordinate>();
coordinates.add(new Coordinate(origin.latitude,origin.longitude,0,0,0,0));
}
public double getArea(){
double ar=0,x1=0,y1=0,x2=0,y2=0;
if(coordinates.size()>2) {
for (int i = 1; i < coordinates.size(); i++) {
x1 = coordinates.get(i).getX();
y1 = coordinates.get(i).getY();
x2 = coordinates.get(i - 1).getX();
y2 = coordinates.get(i - 1).getY();
ar += x1 * y2 - x2 * y1;
}
ar+=x1 *coordinates.get(0).getY()-y1*coordinates.get(0).getX();
ar=Math.abs(ar)/2;
}
return ar;
}
public List<Coordinate> getCoordinates() {
return coordinates;
}
public void addLatLng(LatLng latLng){
double bearing =this.getBearing(latLng);
double distance=this.getDistance(latLng);
double y=distance*Math.cos(bearing);
double x=distance*Math.sin(bearing);
coordinates.add(new Coordinate(latLng.latitude,latLng.longitude,x,y,distance,bearing));
}
public boolean removeLatLan(){
//returns true if Coordinate is removed and false if only last coordinate is left
//does not remove the last coordinate
if(coordinates.size()<=1){
return false;
}
coordinates.remove(coordinates.size()-1);
return true;
}
public List<LatLng> getLatLngList(){
List<LatLng> res=new ArrayList<LatLng>(coordinates.size());
for(Coordinate c:coordinates){
LatLng l=new LatLng(c.getLatitude(),c.getLongitude());
res.add(l);
}
return res;
}
private double getDistance(LatLng latLng){
Coordinate origin=coordinates.get(0);
double ph1=origin.getLatitude()*Math.PI/180;
double ph2=latLng.latitude*Math.PI/180;
double delTa=(latLng.longitude-origin.getLongitude())*Math.PI/180;
double distance=R*Math.acos(Math.sin(ph1)*Math.sin(ph2)+
Math.cos(ph1)*Math.cos(ph2)*Math.cos(delTa));
return distance;
}
private double getBearing(LatLng latLng){
Coordinate origin=coordinates.get(0);
double ph1=origin.getLatitude()*Math.PI/180;
double ph2=latLng.latitude*Math.PI/180;
double delTa=(latLng.longitude-origin.getLongitude())*Math.PI/180;
double y= Math.sin(delTa)*Math.cos(ph2);
double x= Math.cos(ph1)*Math.sin(ph2)-Math.sin(ph1)*Math.cos(ph2)*Math.cos(delTa);
return Math.atan2(y,x);
}
public void setCoordinates(List<Coordinate> coordinates) {
this.coordinates = coordinates;
}
}
Then Comes the Farm Model
public class Farm implements Parcelable{
private static final long serialVersionUID = 1L;
Long id;
String webSafeKey;
Float productivity;
String address;
ArrayList<Area> areas;
public Farm(Context context, com.appspot.myapi.snapapi.model.Farm farm){
this.id = farm.getId();
webSafeKey = farm.getWebSafeKey();
productivity = 0f;
address = farm.getAddress()==null?context.getResources().getString
(R.string.address)
+": "+context.getResources().getString(R.string.NA):farm.getAddress();
areas = new ArrayList<Area>();
for(com.appspot.myapi.snapapi.model.Area areas: farm.getAreas()){
List<LatLng> list = areas.getLatLngList();
Area area = new Area(new com.google.android.gms.maps.model.LatLng(
list.get(0).getLatitude(),list.get(0).getLongitude()
));
for(int i=1;i<list.size();i++){
area.addLatLng(new com.google.android.gms.maps.model.LatLng(
list.get(i).getLatitude(),list.get(i).getLongitude()
));
}
this.areas.add(area);
}
}
protected Farm(Parcel in) {
if (in.readByte() == 0) {
id = null;
} else {
id = in.readLong();
}
webSafeKey = in.readString();
productivity = in.readFloat();
address = in.readString();
areas = new ArrayList<Area>();
in.readTypedList(areas,Area.CREATOR);
// areas = in.readArrayList(null);
}
public static final Creator<Farm> CREATOR = new Creator<Farm>() {
#Override
public Farm createFromParcel(Parcel in) {
return new Farm(in);
}
#Override
public Farm[] newArray(int size) {
return new Farm[size];
}
};
#Override
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeLong(id);
out.writeString(webSafeKey);
out.writeFloat(productivity);
out.writeString(address);
out.writeTypedList(areas);
}
public Double getTotalArea(){
double totalArea=0d;
for(Area area:areas){
totalArea +=area.getArea();
}
return totalArea;
}
public Long getId() {
return id;
}
public String getWebSafeKey() {
return webSafeKey;
}
public float getProductivity() {
return productivity;
}
public String getAddress() {
return address;
}
public ArrayList<Area> getAreas() {
return areas;
}
public void setId(Long id) {
this.id = id;
}
public void setWebSafeKey(String webSafeKey) {
this.webSafeKey = webSafeKey;
}
public void setProductivity(Float productivity) {
this.productivity = productivity;
}
public void setAddress(String address) {
this.address = address;
}
public void setAreas(ArrayList<Area> areas) {
this.areas = areas;
}
}
Now the problem is when I pass Farm class as extras in an Intent and tries to read it in the second Activity, in.readTypedList(areas, Area.CREATOR) gives OutOfMemoryError. To be precise here is the full stacktrace :
java.lang.OutOfMemoryError: Failed to allocate a 30536292 byte allocation with 16041952 free bytes and 15MB until OOM
at java.util.ArrayList.add(ArrayList.java:118)
at android.os.Parcel.readTypedList(Parcel.java:2043)
at in.agrosnap.android.helper.Farm.<init>(Farm.java:60)
at in.agrosnap.android.helper.Farm$1.createFromParcel(Farm.java:67)
at in.agrosnap.android.helper.Farm$1.createFromParcel(Farm.java:64)
at android.os.Parcel.readParcelable(Parcel.java:2367)
at android.os.Parcel.readValue(Parcel.java:2264)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2614)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getParcelable(Bundle.java:786)
at android.content.Intent.getParcelableExtra(Intent.java:5387)
at in.agrosnap.android.FarmDetail.onCreate(FarmDetail.java:79)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Can somebody explain where am I going wrong with this, is the implementation of Marshalling and Unmarshalling User-defined class wrong?
I have used the following references to write this code :
https://www.techjini.com/blog/passing-objects-via-intent-in-android
https://developer.android.com/reference/android/os/Parcel
In your Farm class, you have these two matching methods:
protected Farm(Parcel in) {
if (in.readByte() == 0) {
id = null;
} else {
id = in.readLong();
}
webSafeKey = in.readString();
productivity = in.readFloat();
address = in.readString();
areas = new ArrayList<Area>();
in.readTypedList(areas,Area.CREATOR);
//areas = in.readArrayList(null);
}
public void writeToParcel(Parcel out, int flags) {
out.writeLong(id);
out.writeString(webSafeKey);
out.writeFloat(productivity);
out.writeString(address);
out.writeTypedList(areas);
}
The constructor has a call to in.readByte() that was never written in your writeToParcel() method. It seems like your writeToParcel() should look like this:
public void writeToParcel(Parcel out, int flags) {
if (id != null) {
out.writeByte((byte) 1);
out.writeLong(id);
} else {
out.writeByte((byte) 0);
}
out.writeString(webSafeKey);
out.writeFloat(productivity);
out.writeString(address);
out.writeTypedList(areas);
}
It's not obvious that this would lead to an OutOfMemoryError, but perhaps the parceled data "lines up" well enough until it tries to read the size of the list and gets a huge number because the reads/writes are misaligned.

How can I pass object from ArrayList to new Activity and then receive that? [duplicate]

This question already has answers here:
How to pass ArrayList<CustomeObject> from one activity to another? [duplicate]
(3 answers)
Closed 7 years ago.
I try pass an object to new activity but I have a problem. My ArrayList use another class in this way:
ArrayList<ListData> myList = new ArrayList<>();
All is great, I'm adding to mList a few objects and my listview work fine.
I try pass an object after click in this way:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ListData listdata = myList.get(position);
ListData dataToSend = new ListData();
dataToSend.setStrefa(listdata.getStrefa());
dataToSend.setDzielnica(listdata.getDzielnica());
dataToSend.setAdres(listdata.getAdres());
dataToSend.setKryteria(listdata.getKryteria());
dataToSend.setTelefon(listdata.getTelefon());
dataToSend.setData(listdata.getData());
Intent intent = new Intent(Zlecenia.this, Zlecenie.class);
intent.putExtra("myData", dataToSend);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.no_animation);
}
});
Here is a problem because "bundle.putParcelableArrayList("listdata", listdata);" is marked on red. This forces on me using extends Parcelable in ListData Class but when I added this extends then my ArrayList is empty. What schould I do?
My ListData:
public class ListData implements Parcelable{
String Strefa;
String Adres;
String Kryteria;
String Telefon;
String Data;
String Dzielnica;
String Ilosc;
/* Zlecenia */
public String getStrefa() {
return Strefa;
}
public void setStrefa(String strefa) {
this.Strefa = strefa;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
this.Adres = adres;
}
public String getKryteria() {
return Kryteria;
}
public void setKryteria(String kryteria) {
this.Kryteria = kryteria;
}
public String getTelefon() {
return Telefon;
}
public void setTelefon(String telefon) {
this.Telefon = telefon;
}
public String getData() {
return Data;
}
public void setData(String data) {
this.Data = data;
}
/* Statystyki */
public String getDzielnica() {
return Dzielnica;
}
public void setDzielnica(String dzielnica) {
this.Dzielnica = dzielnica;
}
public String getIlosc() {
return Ilosc;
}
public void setIlosc(String ilosc) {
this.Ilosc = ilosc;
}
public ListData() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Strefa);
dest.writeString(Dzielnica);
dest.writeString(Adres);
dest.writeString(Kryteria);
dest.writeString(Telefon);
dest.writeString(Data);
}
private ListData(Parcel in) {
Strefa = in.readString();
Dzielnica = in.readString();
Adres = in.readString();
Kryteria = in.readString();
Telefon = in.readString();
Data = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR
= new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel in) {
return new ListData(in);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Try this in your class
public class ListData implements Serializable

Categories

Resources