如何将一个对象传递给另一个活动?

18

我需要通过intent将一个类对象传递给另一个activity。以下是我的类代码:

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;
    }
}

1
这段代码是做什么的?发布活动的代码。 - Egor
可能是重复问题:https://dev59.com/m3I95IYBdhLWcg3w1BdN - Pratik
使用 Parcelable 或 Serializable 进行实现。实现示例 - Ali Azaz Alam
3个回答

13

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

仔细阅读为Android编写Parcelable类。在此,他们使用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,用于将对象发送到另一个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());
    }
}

3

您需要在Model类中实现Serializable接口。然后,在源Activity中使用以下代码将Model对象传递到目标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"); - SBJ
同样的问题,错误或日志输出是什么? - Paresh Mayani
问题出在你的代码里。请仔细检查一下。应该这样写:Model modelObject = getIntent().getSerializableExtra("ModelObject"); - Paresh Mayani
是的,我已经编写了与您所描述的相同的代码...语法错误是强制转换错误。更改模型对象为可序列化...我还在我的Model类中实现了序列化。 - SBJ
根据您上面的评论以及此评论http://goo.gl/DsUTT,您可以尝试这样做:Model modelObject =(Model)getIntent()。getSerializableExtra(“ModelObject”); - Paresh Mayani

0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接