I'm trying to pass an Arralyist of some Object with a Double parameter from one activity to another, but after sending it, the Double result is not the same. My Object Producto implements parcelable
import android.os.Parcel;
import android.os.Parcelable;
public class Producto implements Parcelable {
private String nombre, descripcion, url, tipo;
private Double precio;
private int cantidad;
public Producto(String nombre, String descripcion, Double precio, String url, String tipo){
this.nombre = nombre;
this.descripcion = descripcion;
this.precio = precio;
this.tipo = tipo;
this.url = url;
}
protected Producto(Parcel in){
nombre = in.readString();
descripcion = in.readString();
url = in.readString();
tipo = in.readString();
precio = in.readDouble();
cantidad = in.readInt();
}
public static final Creator<Producto> CREATOR = new Creator<Producto>() {
@Override
public Producto createFromParcel(Parcel source) {
return new Producto(source);
}
@Override
public Producto[] newArray(int size) {
return new Producto[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nombre);
dest.writeString(descripcion);
dest.writeString(url);
dest.writeString(tipo);
dest.writeInt(cantidad);
dest.writeDouble(precio);
}
public static Creator<Producto> getCreator(){
return CREATOR;
}
}
I'm trying to send it to the next activity inside an arraylist of products. First Activity
for (DocumentSnapshot doc: listadoProductos
) {
p = new Producto(doc.getString("Nombre"), doc.getString("Descripcion"),
doc.getDouble("Precio"), doc.getString("url2"), doc.getString("Tipo"));
nombres.add(p);
}
Intent intent = new Intent(getApplicationContext(), Productos.class);
intent.putParcelableArrayListExtra("nombres",nombres);
startActivity(intent);
And I've checked that at this moment, the values for Precio are ok, in my case 8.92
But when I received the arraylist in the new Activity, the values are not the same
Second Activity
ArrayList<Producto> listadoProductos = new ArrayList<>()
Intent intent = getIntent();
if (intent.getParcelableArrayListExtra("nombres")!= null) {
listadoProductos = intent.getParcelableArrayListExtra("nombres");
Here, the new value is 9.458744551493758E-13 Anyone could explain what's going on and how to get the real value of 8.92?
While working with parcelable you must have the correct order in place.
When reading your fields you must have the same order as you was writing them. Here you have:
// writing: first cantidad then precio
dest.writeInt(cantidad);
dest.writeDouble(precio);
// reading is reversed.
precio = in.readDouble();
cantidad = in.readInt();
just change the order
cantidad = in.readInt();
precio = in.readDouble();
And it should work