0

That's my question more or less... I've got a class that extends from Exception and I need it to be inserted in a parcel.

How can I achieve that?

public class Result implements Parcelable
{
    public Result(UserException exception){
        this.exception = exception;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
    if (exception != null){
        // What to do here  ant to un-parcel it?
    }
    }
}

My class:

public class UserException extends Exception
{
string message;
public UserException() {
    super();
}

public UserException(String message, Throwable cause)
{
    super(message, cause);

    this.cause = cause;
    this.message = message;
}
}
Sonhja
  • 8,230
  • 20
  • 73
  • 131
  • I'm not sure about it, I will search later but I believe that you can insert into a parcel a parcelable object so you need to implements Parcelable in your exception to be able to add it in the Parcel. – AxelH Feb 24 '15 at 11:17
  • That's what I made just now, but I guess it should be an adequate way using parcels... – Sonhja Feb 24 '15 at 11:28
  • dest.writeException((Exception) exception); have you tried this? – Arslan Sohail Feb 24 '15 at 11:30
  • @Arslan I'm not sure this will pass, the doc says that this supported only a few Exception. – AxelH Feb 24 '15 at 12:06
  • @Sonhja This is the roght way to use the Parcels. This give you the possiblities to store complex Object with multiple relation. – AxelH Feb 24 '15 at 12:07

1 Answers1

1
@Override
public void writeToParcel(Parcel dest, int flags) {
   if (exception != null){
       dest.writeParcelable(exception, flags);
   }
}

And in the exception :

public class UserException extends Exception implements Parcelable{
   //Lot of fun to be Parcelable
}

And you can read it like this :

exception = (UserException)in.readParcelable(UserException.class.getClassLoader());

Or better like this

exception = in.<UserException>readParcelable(UserException.class.getClassLoader());
AxelH
  • 14,325
  • 2
  • 25
  • 55