How to pass a class with Bigdecimal and Date attribute through intents(Bundle)?

Asked

Viewed 182 times

2

I have a ArrayList<MinhaClasse> with Bigdecimal attribute and I am going through Intent from one activity to another. The problem is that the Bigdecimal attribute passes with null value.

Can’t you pass a Bigdecimal attribute? I’m with an attribute date with same problem.

  • What Minhaclasse implements, Serializable or Parcelable?

  • She implements Parcelable

1 answer

1


Has (at least) two possibilities:

  • Make Minhaclasse implement Serializable, which is not advisable for this purpose(1).
    Date and Bigdecimal implement Serializable, they will be processed without problem.
    Must use getSerializableExtra()instead of getParcelableExtra().

  • Change Minhaclasse to store in Parcel a String and a long with Bigdecimal and Date values. They, after retrieved, are used to recreate them.

    public class ClassParcelable implements Parcelable{
    
        private Date someDate;
        private BigDecimal someBigValue;
    
        public ClassParcelable(Date someDate, BigDecimal someBigValue){
            this.someDate = someDate;
            this.someBigValue = someBigValue;
        }
    
        //Implementação da Parcelable
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
    
            //Guarda um long que representa a data
            dest.writeLong(someDate.getTime());
    
            //Guarda uma String com a representação do valor do BigDecimal
            dest.writeString(someBigValue.toPlainString());
        }
    
        protected ClassParcelable(Parcel in) {
    
            //Recupera o long que representa a data e recria-a
            someDate = new Date(in.readLong());
            //Recupera a String que representa o valor do BigDecimal e recria-o
            someBigValue = new BigDecimal(in.readString());
        }
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        public static final Creator<ClassParcelable> CREATOR = new Creator<ClassParcelable>() {
            @Override
            public ClassParcelable createFromParcel(Parcel in) {
                return new ClassParcelable(in);
            }
    
            @Override
            public ClassParcelable[] newArray(int size) {
                return new ClassParcelable[size];
            }
        };
    }
    

(1) - Reflection is used during the process and many additional objects are created, which can cause a lot of garbage collection. The result is poor performance and high battery consumption.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.