所以我有活动A和活动B,在“ A”中,我需要转到“ B”,然后将Food项目添加到它们的arrayList中,然后将此数组列表传递回Activity A,我如何解决我的问题当前设置

这是从A到B的意图

Intent i = new Intent(OrderMain.this , OrderAdd.class);
startActivityForResult(i,1);


这是从B到A的返回意图

Intent returnIntent = new Intent();
Bundle b = new Bundle();
b.putSerializable("results", orderArray);
returnIntent.putExtras(b);
setResult(Activity.RESULT_OK, returnIntent);
finish();


最后是我的A中的onActivityResults

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            Bundle b = getIntent().getExtras();
            ArrayList<Food> test = new ArrayList<>();
            test = (ArrayList<Food>) b.getSerializable("results");
            setOrderArray(test);
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}


setOrderArray只是将Array设置为新返回的Array的函数

这就是食物对象

import java.io.Serializable;

public class Food implements Serializable{
    private String name;
    private int cost;
    private int quantity;

public Food( String name, int cost, int quantity){
        this.name = name;
        this.cost = cost;
        this.quantity = quantity;
    }
    public void setQuantity(int quantity)
    {
        this.quantity = quantity;
    }
    public void setName(String name)
    {
       this.name = name;
    }
    public void setCost(int cost)
    {
        this.cost = cost;
    }
    public int getTotal()
    {
        return cost * quantity;
    }
    public String getName ()
    {
        return name;
    }
    public int getCost()
    {
        return cost;
    }
    public int getQuantity()
    {
        return quantity;
    }
    public void addQuantity()
    {
        quantity++;
    }
    public void decQuantity()
    {
        quantity--;
    }
}


我当前遇到的问题是此代码行:

test = (ArrayList<Food>) b.getSerializable("results");


据说存在“未经检查的演员表”,并且此功能的预期用途无法正常运行,我们将不胜感激

最佳答案

因为您从错误的意图中获取数据。您应该从

Bundle b = getIntent().getExtras();
ArrayList<Food> test = new ArrayList<>();
test = (ArrayList<Food>) b.getSerializable("results");




ArrayList<Food> test = (ArrayList<Food>) data.getSerializableExtra("results");

07-24 19:24