【问题标题】:How to pass an object to another activity? [duplicate]如何将对象传递给另一个活动? [复制]
【发布时间】:2011-10-08 06:08:56
【问题描述】:

我需要通过意图将一个类对象传递给另一个活动。这是我的课程代码:

public class Model
{
    private String Name;
    private ArrayList<Trim> trim;

    public String getName()
    {
        return Name;
    }

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

    public ArrayList<Trim> getTrim()
    {
        return trim;
    }

    public void setTrim(ArrayList<Trim> trim)
    {
        this.trim = trim;
    }
}

【问题讨论】:

标签: android android-intent android-activity


【解决方案1】:

要将对象传递给另一个活动,您需要实现 Parcelable。

仔细查看Writing Parcelable classes for Android。在这里,他们使用 Hashmap 来存储值并将对象传递给另一个类。


创建一个类,ObjectA。其中,我使用了所有的 setter 和 getter 方法。

package com.ParcableExample.org;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * A basic object that can be parcelled to
 * transfer between objects.
 */

public class ObjectA implements Parcelable
{
    private String strValue = null;
    private int intValue = 0;

    /**
     * Standard basic constructor for non-parcel
     * object creation.
     */

    public ObjectA()
    {
    }

    /**
     *
     * Constructor to use when re-constructing object
     * from a parcel.
     *
     * @param in a parcel from which to read this object.
     */

    public ObjectA(Parcel in)
    {
        readFromParcel(in);
    }

    /**
     * Standard getter
     *
     * @return strValue
     */
    public String getStrValue()
    {
        return this.strValue;
    }

    /**
     * Standard setter
     *
     * @param strValue
     */

    public void setStrValue(String strValue)
    {
        this.strValue = strValue;
    }


    /**
     * Standard getter
     *
     * @return intValue
     */
    public Integer getIntValue()
    {
        return this.intValue;
    }

    /**
     * Standard setter
     *
     * @param strValue
     */
    public void setIntValue(Integer intValue)
    {
        this.intValue = intValue;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags)
    {
        // We just need to write each field into the
        // parcel. When we read from parcel, they
        // will come back in the same order

        dest.writeString(this.strValue);
        dest.writeInt(this.intValue);
    }

    /**
     *
     * Called from the constructor to create this
     * object from a parcel.
     *
     * @param in parcel from which to re-create object.
     */
    public void readFromParcel(Parcel in)
    {
        // We just need to read back each
        // field in the order that it was
        // written to the parcel

        this.strValue = in.readString();
        this.intValue = in.readInt();
    }

    /**
    *
    * This field is needed for Android to be able to
    * create new objects, individually or as arrays.
    *
    * This also means that you can use use the default
    * constructor to create the object and use another
    * method to hyrdate it as necessary.
    */
    @SuppressWarnings("unchecked")
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
    {
        @Override
        public ObjectA createFromParcel(Parcel in)
        {
            return new ObjectA(in);
        }

        @Override
        public Object[] newArray(int size)
        {
            return new ObjectA[size];
        }
    };
}

然后制作一个 Activity 用于将 Object 发送到另一个 Activity。

package com.ParcableExample.org;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ParcableExample extends Activity
{
    private Button btnClick;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initControls();
    }

    private void initControls()
    {
        btnClick = (Button)findViewById(R.id.btnClick);
        btnClick.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                ObjectA obj = new ObjectA();
                obj.setIntValue(1);
                obj.setStrValue("Chirag");

                Intent i = new Intent(ParcableExample.this,MyActivity.class);
                i.putExtra("com.package.ObjectA", obj);
                startActivity(i);
            }
        });
    }
}

现在终于创建另一个读取对象并从中获取值的活动。

package com.ParcableExample.org;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MyActivity extends Activity
{
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bundle bundle = getIntent().getExtras();
        ObjectA obj = bundle.getParcelable("com.package.ObjectA");

        Log.i("---------- Id   ",":: "+obj.getIntValue());
        Log.i("---------- Name ",":: "+obj.getStrValue());
    }
}

【讨论】:

    【解决方案2】:

    你的类应该实现Parcelable 接口,然后你可以将它发送到另一个Activity 使用:

    MyClass myObject;
    //...
    intent=new Intent(this, MyAnotherActivity.class);
    intent.putExtra("mydata", (Parcelable )myObject);
    this.startActivity(intent);
    

    【讨论】:

      【解决方案3】:

      您需要在 Model 类中实现 Serializable。然后,要将Model 对象从源Activity 传递到目标Activity,请在源Activity 中使用以下代码:

      Model objModel = new Model();
      Intent modelActivity = (Model.this, detail.class);
      intent.putExtra("ModelObject", objModel);
      

      而这个代码在目的地Activity:

      Model modelObject = getIntent().getSerializableExtra("ModelObject");
      

      【讨论】:

      • 嗨,感谢您的回复.. 但是当在目标活动中收到相同的对象而不是语句中的错误... model = this.getIntent().getSerializableExtra("ModelClass");
      • 同样的错误或 logcat 输出是什么?
      • 那么问题出在您的代码中。正确检查。你应该写:Model modelObject = getIntent().getSerializableExtra("ModelObject");
      • 是的,我写的代码和你描述的一样...语法错误是转换错误。更改模型对象是可序列化的...我也在我的模型类中实现了序列化。
      • 根据您的上述评论和此评论goo.gl/DsUTT,您可以试试这个:Model modelObject = (Model) getIntent().getSerializableExtra("ModelObject");
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多