Подтвердить что ты не робот

Как передать объект другому мероприятию?

Мне нужно передать объект класса другому действию с помощью намерения. Вот мой код класса:

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

Ответ 1

Чтобы передать объект другому действию, вам необходимо реализовать Parcelable.

Внимательно просмотрите Написание Parcelable classes для 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];
        }
    };
}

Затем создайте одно действие, которое используется для отправки объекта в другое действие.

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

Вам нужно реализовать Serializable в вашем классе Model. Затем, чтобы передать объект Model из источника Activity в пункт назначения Activity, используйте следующий код в источнике Activity:

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

И этот код в пункте назначения Activity:

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

Ответ 3

Ваш класс должен реализовать интерфейс Parcelable, а затем вы можете отправить его другому Activity, используя:

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