提问者:小点点

我如何才能只发送一个列表的少数选定的项目到另一个activity使用意图?


该应用是一款订餐应用。 我使用Intent从数组中的许多菜肴中只添加了几个菜肴。在我单击“继续到购物车”按钮之后,我怎样才能在另一个activity中看到我的菜肴,而这些菜肴只是添加的。

这是我在数组中添加盘子的代码。

 val desc = dishList[position]
        holder.txtDishName.text = desc.desName
        holder.txtCost_for_one.text = desc.desCost_for_one
        holder.btnAdd.setOnClickListener {
            if (holder.btnAdd.text == "ADD") {
                val obj = Cart(
                    desc.id,
                    desc.desName,
                    desc.desCost_for_one,
                    desc.restaurant_id
                )
                addToCart.add(obj)
                holder.btnAdd.text = "Remove"
                val favColor = ContextCompat.getColor(this.context, R.color.colorPrimary)
                holder.btnAdd.setBackgroundColor(favColor)

            } else{
               for (i in 0 until addToCart.size ){
                   if (addToCart[i].cId == desc.id){
                       addToCart.removeAt(i)
                   }
               }
                holder.btnAdd.text = "Add"
                val favColor = ContextCompat.getColor(this.context, R.color.colorAccent)
                holder.btnAdd.setBackgroundColor(favColor)
            }
            val intent = Intent(context, DescriptionActivity::class.java)
            intent.putExtra("addToCart",addToCart)
            

        }
        
    }

这是我点击proceed to cart按钮的代码。

btnProceed.setOnClickListener {
            val intent = Intent(this, CartActivity::class.java)
            //intent.getStringArrayExtra("addToCart")
            intent.getStringExtra("addToCart")
            startActivity(intent)

但运行应用程序后,CartActivity变为空。


共2个答案

匿名用户

如果e类型是serializable,则可以以相同的方式传递ArrayList

即:在e中实现serializable

您可以调用intentputExtra(字符串名,可序列化值)来存储,调用GetSerializableExtra(字符串名)来检索。

例如

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

在其他activity收到:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

匿名用户

如果您想使用字符串,我认为您应该将列表转换为JSON。

例如,使用Gson

var gson = Gson()
val myObject = myObject(...)
val jsonString = gson.toJson(myObject)
intent.putExtra("myObjectKey", jsonString)

然后你就可以得到这样的字符串

val jsonString = intent.getStringExtra("myObjectKey")
var myObject = gson.fromJson(jsonString, myObject::class.java)

用于使用Gson

实现'com.google.code.gson:gson:2.8.6'