39

我想从另一个活动传递一个活动的对象列表。我在下面有一堂SharedBooking

public class SharedBooking {
  public int account_id;
  public Double betrag;
  public Double betrag_effected;
  public int taxType;
  public int tax;
  public String postingText;
}

调用活动的代码:

public List<SharedBooking> SharedBookingList = new ArrayList<SharedBooking>();

public void goDivision(Context context, Double betrag, List<SharedBooking> bookingList) {
  final Intent intent = new Intent(context, Division.class);    
  intent.putExtra(Constants.BETRAG, betrag);        
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  context.startActivity(intent);        
}

调用活动的代码:

Bundle extras = getIntent().getExtras();
if (extras != null) {
  amount = extras.getDouble(Constants.BETRAG,0);
}

如何从一项活动发送 SharedBooking 列表并在另一项活动中接收?

请建议我任何可用的链接或示例代码。

4

9 回答 9

99

首先,使列表的类实现Serializable

public class MyObject implements Serializable{}

然后你可以将列表转换为(Serializable)。像这样:

List<MyObject> list = new ArrayList<>();
myIntent.putExtra("LIST", (Serializable) list);

并检索您执行的列表:

Intent i = getIntent();
list = (List<MyObject>) i.getSerializableExtra("LIST");

就是这样。

于 2015-08-12T17:53:37.270 回答
52

使用parcelable。以下是您将如何做到的:

public class SharedBooking implements Parcelable{

    public int account_id;
    public Double betrag;
    public Double betrag_effected;
    public int taxType;
    public int tax;
    public String postingText;

    public SharedBooking() {
        account_id = 0;
        betrag = 0.0;
        betrag_effected = 0.0;
        taxType = 0;
        tax = 0;
        postingText = "";
    }

    public SharedBooking(Parcel in) {
        account_id = in.readInt();
        betrag = in.readDouble();
        betrag_effected = in.readDouble();
        taxType = in.readInt();
        tax = in.readInt();
        postingText = in.readString();
    }

    public int getAccount_id() {
        return account_id;
    }
    public void setAccount_id(int account_id) {
        this.account_id = account_id;
    }
    public Double getBetrag() {
        return betrag;
    }
    public void setBetrag(Double betrag) {
        this.betrag = betrag;
    }
    public Double getBetrag_effected() {
        return betrag_effected;
    }
    public void setBetrag_effected(Double betrag_effected) {
        this.betrag_effected = betrag_effected;
    }
    public int getTaxType() {
        return taxType;
    }
    public void setTaxType(int taxType) {
        this.taxType = taxType;
    }
    public int getTax() {
        return tax;
    }
    public void setTax(int tax) {
        this.tax = tax;
    }
    public String getPostingText() {
        return postingText;
    }
    public void setPostingText(String postingText) {
        this.postingText = postingText;
    }
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(account_id);
        dest.writeDouble(betrag);
        dest.writeDouble(betrag_effected);
        dest.writeInt(taxType);
        dest.writeInt(tax);
        dest.writeString(postingText);

    }

    public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
    {
        public SharedBooking createFromParcel(Parcel in)
        {
            return new SharedBooking(in);
        }
        public SharedBooking[] newArray(int size)
        {
            return new SharedBooking[size];
        }
    };

}

传递数据:

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("data", sharedBookingObject);
intent.putExtras(bundle);
startActivity(intent);

检索数据:

Bundle bundle = getIntent().getExtras();
sharedBookingObject = bundle.getParcelable("data");
于 2012-08-23T13:39:12.557 回答
11

可打包对象类

    public class Student implements Parcelable {

        int id;
        String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;

        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }


        @Override
        public int describeContents() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int arg1) {
            // TODO Auto-generated method stub
            dest.writeInt(id);
            dest.writeString(name);
        }

        public Student(Parcel in) {
            id = in.readInt();
            name = in.readString();
        }

        public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
            public Student createFromParcel(Parcel in) {
                return new Student(in);
            }

            public Student[] newArray(int size) {
                return new Student[size];
            }
        };
    }

和名单

ArrayList<Student> arraylist = new ArrayList<Student>();

调用活动的代码

Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", arraylist);
intent.putExtras(bundle);       
this.startActivity(intent);

调用活动的代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);   

    Bundle bundle = getIntent().getExtras();
    ArrayList<Student> arraylist = bundle.getParcelableArrayList("mylist");
}
于 2015-01-27T15:20:44.687 回答
2

您可能希望在SharedBooking类中实现Parcelable接口并将它们添加到 Intent 中,即使用putParcelableArrayListExtra方法。检查文档

于 2012-08-23T13:33:09.857 回答
1

您还可以使用 将列表转换为字符串Gson,然后像这样传递它:

String yourListAsString = new Gson().toJson(yourList);
bundle.putString("data",yourListAsString);

然后使用您的类作为类型检索它:

List<YourList> listName = new Gson().fromJson("data", new TypeToken<List<YourList>>(){}.getType());
于 2020-07-14T08:00:22.010 回答
0

有两种方法可以将对象数组列表或对象从一个活动发送到另一个活动:

  1. 可包裹
  2. 可序列化
于 2020-06-09T16:48:56.337 回答
0

如果有人正在寻找答案,这就是我使用 Kotlin 实现它的方式。

可打包对象类

data class CollectedMilk(
    @SerializedName("id")
    var id: Int,
    @SerializedName("igicuba")
    var igicuba: Int,
    @SerializedName("collector")
    var collector: String?,
    @SerializedName("collected")
    var collected: Int,
    @SerializedName("accepted")
    var accepted: Int,
    @SerializedName("standard")
    var standard: String?,
    @SerializedName("created_at")
    var created_at: String?,
    @SerializedName("updated_at")
    var updated_at: String?,
): Parcelable {

    constructor(parcel: Parcel) : this(
        parcel.readInt(),
        parcel.readInt(),
        parcel.readString(),
        parcel.readInt(),
        parcel.readInt(),
        parcel.readString(),
        parcel.readString(),
        parcel.readString()
    )

    override fun describeContents(): Int {
        return 0
    }

    override fun writeToParcel(parcel: Parcel?, int: Int) {
        parcel?.writeInt(id)
        parcel?.writeInt(igicuba)
        parcel?.writeString(collector)
        parcel?.writeInt(collected)
        parcel?.writeInt(accepted)
        parcel?.writeString(standard)
        parcel?.writeString(created_at)
        parcel?.writeString(updated_at)
    }

    companion object CREATOR : Parcelable.Creator<CollectedMilk> {
        override fun createFromParcel(parcel: Parcel): CollectedMilk {
            return CollectedMilk(parcel)
        }

        override fun newArray(size: Int): Array<CollectedMilk?> {
            return arrayOfNulls(size)
        }
    }
}

然后在片段中

collectedMilkAdapter.onItemClick = { collectedMilk ->
            Toast.makeText(
                MccApp.applicationContext(),
                "Collector: " + collectedMilk.collector,
                Toast.LENGTH_LONG
            ).show()

            val intent = Intent(MccApp.applicationContext(), CollectedMilkActivity::class.java)
            val bundle: Bundle = Bundle()

            bundle.putParcelableArrayList("collectedMilk", collectedMilkArrayList)
            intent.putExtras(bundle)

            activity?.startActivity(intent)
        }

然后在另一个活动上我的详细活动

全局变量

private lateinit var collectedMilk: ArrayList<CollectedMilk>

在函数或 OnCreate 活动中

val bundle = intent.extras
        collectedMilk = (bundle?.getParcelableArrayList<CollectedMilk>("collectedMilk") as ArrayList<CollectedMilk>)

        Toast(this).showCustomToast(
            this,
            ""+collectedMilk,
            dark
        ) 
于 2020-10-02T14:14:28.597 回答
0

另一种选择是使用 Gson。

将此扩展名复制到您的代码中:

// will write a list of objects to intent
fun Intent.putExtra(name: String, objs: List<*>) = putExtra(name, Gson().toJson(objs))

// will read a list of objects from intent
inline fun <reified T> Intent.getObjListExtra(name: String): List<T>? {
    val lstStr = getStringExtra(name) ?: return null
    val lst = Gson().fromJson<List<T>>(lstStr, object: ParameterizedType {
        override fun getActualTypeArguments(): Array<Type> = arrayOf(T::class.java)
        override fun getRawType(): Type = List::class.java
        override fun getOwnerType(): Type = T::class.java
    })
    return lst
}

并使用它们:

活动一:

startActivity(Intent(this, Activity2::class.java).also {
   val people = listOf(Person("Moishe"), Person("Albert"), Person("Lezly"))
   it.putExtra("people", people)
 })

活动二:

val people = intent.getObjExtra<Person>("Person")

该解决方案旨在使用 Gson 作为解析器

于 2020-12-15T15:31:47.847 回答
0

科特林

首先,使列表的类实现Serializable

class MyObject: Serializable{}

然后你可以将列表转换为(Serializable)。像这样:

val list: List<MyObject> = mutableListOf<MyObject>();
myIntent.putExtra("LIST", list as Serializable);

并检索您执行的列表:

val mlist = intent.getSerializableExtra("LIST") as? List<ModuleDataRow>

就是这样。

于 2021-08-29T08:07:44.503 回答