从活动到另一个活动的自定义对象

问题描述:

我尝试从活动向另一个活动发送信息时遇到了一些问题。我想发送一些自定义对象。我将它们加载到我的第一个活动中,因为优化,但现在我想让它们处于将使用它们的活动中,所以我的想法是放置额外的东西并获得额外的东西,但是我无法得到它们,因为我不是真的知道如何使用投入额外的定制方法从活动到另一个活动的自定义对象

这是我的目标:

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:对不起,我的英语。

这样做的一个正确方法是在你的班级中实现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 –

将核心或bean类设置为parcelable,以便您可以在组件之间发送对象。

这里是示例parcelable example

实现Parcelable和使用意图通过自定义对象。

您可以使用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()); 
     }