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

时间:2015-04-27 06:37:53

标签: java android android-activity

尝试将活动信息发送给其他人时,我遇到了一些问题。我想发送一些自定义对象。我在第一次活动中加载它们,因为优化,但现在我想让它们进入将使用它们的活动所以我的想法是添加额外的东西并得到额外的东西但是我不能得到它们因为我不是真的知道如何使用额外的自定义方法

这是我的目标:

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

4 个答案:

答案 0 :(得分:1)

这样做的一种正确方法是在您的班级中实施Parcelable。 这个答案显示了如何实现它:

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

您可以按照上面的答案中的说明手动执行此操作,也可以使用此功能 http://www.parcelabler.com/ 它直接提供了Parcelable的实现。

之后,您可以通过意图传递您的对象。

答案 1 :(得分:0)

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

这是示例parcelable example

答案 2 :(得分:0)

实现Parcelable并使用Intents传递自定义对象。

答案 3 :(得分: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());
        }