2014-02-07 32 views
-1

於是我開始通過創建一個自定義對象「尚書」Android的意圖的額外返回null屬性

Book b = new Book(id, title.getText().toString(),authors , isbn.getText().toString(), "$9.99"); 

所有這些參數的定義,而不是空。接下來,我將對象「b」並將其置於意圖如下:

resultIntent.putExtra(BOOK_RESULT_KEY, b); 

還是不錯的。檢索這裏的對象獲取什麼被放了進去,果然:

Book test = (Book) resultIntent.getExtras().get(BOOK_RESULT_KEY); 

完成並返回到父活動的意圖的結果:

setResult(RESULT_OK, resultIntent); 
finish(); 

關父活動:

Book b = (Book) intent.getExtras().get(AddBookActivity.BOOK_RESULT_KEY); 

這裏存在這個問題。這本書的所有屬性都在那裏,除了作者[]。我得到的是一個長度正確的數組(作者[]),但數組中的每個元素現在都是空的。當它被置於意圖中時,我百分之百的積極。爲什麼我不能得到這個數組的內容?

+0

您的Book類是否可以實現可分辨? – Raghunandan

+0

您不能直接在Intent中傳遞對象。你需要將它作爲'Bundle'傳遞並從'Bundle'中獲取。 – GrIsHu

+0

已經實現Book類與parcelable? –

回答

0

在下一個活動中使用書籍作爲工具Serialisable和getserialisable對象。

+1

如果他處理了Parcelable,那麼問題是什麼?爲什麼可串行化,如果Android給了Parcelable? –

+0

兩者都是相同的功能,但我使用serialisable.parcelable做也是不錯的:) – Amish

+0

我親愛的朋友在android serializable是不好的。 –

2

你需要讓你的BookParcelable類,然後你可以把它作爲Parcelable數組Bundle,並直接從Bundle得到它。

時退房Simple Parcelable Example

假設你的代碼

public class Book implements Parcelable{ 

    private String id; 
    private String title; 
    private String authors; 
    private String isbn; 
    private String price; 
    // Constructor 
    public Student(String id, String title, String authors,String isbn,String price){ 
     this.id = id; 
     this.title= title; 
     this.authors = authors; 
     this.isbn=isbn; 
     this.price=price; 
    } 

    ...................................... 
     // Parcelling part 
    public Book(Parcel in){ 
     String[] data = new String[5]; 

     in.readStringArray(data); 
     this.id = data[0]; 
     this.title= data[1]; 
     this.authors= data[2]; 
     this.isbn= data[3]; 
     this.price= data[4]; 
    } 

    @Оverride 
    public int describeContents(){ 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeStringArray(new String[] {this.id, 
              this.title, 
              this.authors,this.isbn,this.price}); 
    } 
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 
     public Book createFromParcel(Parcel in) { 
      return new Book(in); 
     } 

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

現在創建Parcelable類,你可以傳遞數據如下之後:

resultIntent.putExtra(BOOK_RESULT_KEY,new Book(id, title.getText().toString(),authors , isbn.getText().toString(), "$9.99")); 

獲取從包中的數據如下:

Bundle data = getIntent().getExtras(); 

Book b = (Book)data.getParcelable(AddBookActivity.BOOK_RESULT_KEY);