2015-08-24 20 views
-1

我想使用類中的Parcelable將活動中的對象發送給另一個對象。我有一個Parcelable類,它有兩個字符串和一個Exception作爲屬性。可作爲屬性的異常類(Android)的可執行類

public class ReportErrorVO implements Parcelable { 

    private String titleError; 
    private String descriptionError; 
    private Exception exceptionError; 

    public ReporteErrorVO(Parcel in) { 
     titleError = in.readString(); 
     descriptionError = in.readString(); 
     exceptionError = ????; //What do I put here? 
    } 

    public ReporteErrorVO() { 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) {  
     dest.writeString(titleError); 
     dest.writeString(descriptionError); 
     dest.writeException(exceptionError); 
    } 

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 
     public ReportErrorVO createFromParcel(Parcel in) { 
      return new ReportErrorVO(in); 
     } 

     public ReportErrorVO[] newArray(int size) { 
      return new ReportErrorVO[size]; 
     } 
    }; 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    //Getter and setters atributes... 
} 

如何在parcelable屬性中設置異常?

+1

更正了拼寫。 –

回答

0

好了的,這樣做,幫我把事情的工作:發送陣列上的異常。

@Override 
    public void writeToParcel(Parcel dest, int flags) {  
     dest.writeString(mTitleError); 
     dest.writeString(mDescriptionError); 
     Exception[] exceptions = new Exception[1]; 
     exceptions[0] = mExceptionError; 
     dest.writeArray(exceptions); 
    } 

public ReportErrorVO(Parcel in) { 
     mTitleError = in.readString(); 
     mDescriptionError = in.readString(); 
     Object[] exceptions = in.readArray(Exception.class.getClassLoader()); 
     mExceptionError = (Exception) exceptions[0]; 
    } 
0

您可以使用readException方法in.readException(),如果該方法已被寫入包裹,此方法將引發異常,因此您可以將其捕獲並保存到變量中。

try { 
     in.readException(); 
    } catch (Exception e){ 
     exceptionError = e; 
    } 

注意,此方法只支持有限的異常類型

The supported exception types are: 
    * BadParcelableException 
    * IllegalArgumentException 
    * IllegalStateException 
    * NullPointerException 
    * SecurityException 
    * NetworkOnMainThreadException 
+0

以及我必須在writeToParcel方法中寫入異常?因爲我使用它的方式,我得到IllegalStateException:無法執行活動的方法(我可能認爲該例外正在執行) –

相關問題