2015-04-27 48 views
-1

我嘗試從活動向另一個活動發送信息時遇到了一些問題。我想發送一些自定義對象。我將它們加載到我的第一個活動中,因爲優化,但現在我想讓它們處於將使用它們的活動中,所以我的想法是放置額外的東西並獲得額外的東西,但是我無法得到它們,因爲我不是真的知道如何使用投入額外的定製方法從活動到另一個活動的自定義對象

這是我的目標:

public class VMyCode{ 

    private String name; 
    private ArrayList<GeneticStep> code; 
    private int image; 

    public VMyCode(){ 
     this.name = null; 
     this.code = null; 
     this.image = -1; 
    } 

    public VMyCode(String name, ArrayList<GeneticStep> code, int image){ 
     this.name = name; 
     this.code = code; 
     this.image = image; 
    } 

    public int getImage() { 
     return image; 
    } 

    public String getName() { 
     return name; 
    } 

    public ArrayList<GeneticStep> getCode() { 
     return code; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public void setCode(ArrayList<GeneticStep> code) { 
     this.code = code; 
    } 

    public void setImage(int image) { 
     this.image = image; 
    } 
} 

我想要做的是從第一個活動發送VMyCode的ArrayList和獲得它的其他活動。

我試圖讓我的對象實現Serializable,並將getSerializableExtras 轉換成ArrayList,但看起來不像它的工作。

如果有人有一些想法,隨時分享!謝謝

Ps:對不起,我的英語。

回答

1

這樣做的一個正確方法是在你的班級中實現Parcelable。 這個答案說明如何實現它:

https://stackoverflow.com/a/7181792/2534007

在上面的答案解釋,您可以手動執行此操作,或者你可以使用這個 http://www.parcelabler.com/ 直接提供實現Parcelable的。

之後,您可以通過意向傳遞您的對象。

+0

以及感謝非常有用的,做我想要的東西!問題依然存在:我的自定義對象VMyCode使用GeneticStep這是一個自定義對象,它是否應該實現Parcelable?如果是這樣,我的所有自定義對象是否應該用於可能由VMyCode使用的對象或GeneticStep實現Parcelable? – Nico

+0

是的,你必須在這些類中實現Parcelable。請參考這個問題,它會幫助你實現自定義parcelable類的列表:http://stackoverflow.com/questions/14178736/how-to-make-a-class-with-nested-objects-parcelable –

0

將核心或bean類設置爲parcelable,以便您可以在組件之間發送對象。

這裏是示例parcelable example

0

實現Parcelable和使用意圖通過自定義對象。

0

您可以使用parceble: 因爲有以前那樣喜歡:

setclass d = new setclass(); 
       d.setDt(5); 
       LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>(); 
       obj.put("hashmapkey", d); 
      Intent inew = new Intent(SgParceLableSampelActivity.this, 
        ActivityNext.class); 
      Bundle b = new Bundle(); 
      b.putSerializable("bundleobj", obj); 
      inew.putExtras(b); 
      startActivity(inew); 

而對於另一活動獲取值:

try { setContentView(R.layout.main); 
      Bundle bn = new Bundle(); 
      bn = getIntent().getExtras(); 
      HashMap<String, Object> getobj = new HashMap<String, Object>(); 
      getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj"); 
      setclass d = (setclass) getobj.get("hashmapkey"); 
     } catch (Exception e) { 
      Log.e("Err", e.getMessage()); 
     } 
相關問題