Android错误java.util.ArrayList无法转换为android.os.Parcelable

时间:2019-06-26 03:06:28

标签: android

我正在尝试将购物车商品列表从1个活动传递到另一个活动,以便用户可以在结帐之前获得关于订单的最后1个视图。问题是当我运行它时出现错误java.util.ArrayList cannot be cast to android.os.Parcelable 有人可以帮助我解决这个问题吗?

这是意图代码

    Intent i = new Intent(CreateNewReceiptActivity.this,ViewFinalReceiptActivity.class);
                    i.putExtra("receiptcart", (Parcelable) itemList);
                startActivity(i);

这就是我收到意图的方式

 itemList = (List<Item>) getIntent().getParcelableExtra("receiptcart");

这是完整的代码 购物车代码:

public class CreateNewReceiptActivity extends BaseActivity {


    Task<QuerySnapshot> searchitemMerkfilter;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    ItemAdapter adapter;
    List<Item> itemList;
    Item item;
    @BindView(R.id.new_receipt_date)
    TextView date;
    @BindView(R.id.new_receipt_checkstock_itemname)
    EditText etItemType;
    @BindView(R.id.new_receipt_checkstock_itembrand)
    EditText etItemBrand;
    @BindView(R.id.new_receipt_btn_check_stock)
    Button btnCheckStock;
    @BindView(R.id.new_receipt_pb_loading)
    ProgressBar pbLoading;
    @BindView(R.id.new_receipt_tv_tersedia)
    TextView tersedia;
    @BindView(R.id.new_receipt_tv_tidakterdaftar)
    TextView tidakTerdaftar;
    @BindView(R.id.new_receipt_adddetail_itemqty)
    EditText etItemQty;
    @BindView(R.id.new_receipt_adddetail_itemprice)
    EditText etItemPrice;
    @BindView(R.id.new_receipt_adddetail_btn_add_item)
    Button btnAddItem;
    @BindView(R.id.new_receipt_cartitem_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.new_receipt_cartitem_btn_checkout)
    Button btnCheckOut;
    @BindView(R.id.cv_add_detail_item)
    CardView cvDetailItem;
    @BindView(R.id.new_receipt_btn_qr_scan)
    ImageButton qrScanner;
    String itemType, itemBrand, itemid, itemQty, itemPrice, itemDate;
    private IntentIntegrator qrScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_new_receipt);
        etItemType.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
        etItemBrand.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
        itemList = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ItemAdapter(this, itemList);
        recyclerView.setAdapter(adapter);
        setDate(date);

        qrScan = new IntentIntegrator(this);

                qrScanner.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        qrScan.initiateScan();
                    }
                });

        btnCheckStock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                itemType = etItemType.getText().toString();
                itemBrand = etItemBrand.getText().toString();
                tersedia.setVisibility(View.GONE);
                tidakTerdaftar.setVisibility(View.GONE);

                if (itemType.isEmpty()) {
                    searchitemMerkfilter = db.collection("watchlist").whereEqualTo("merk", itemType).get();
                    pbLoading.setVisibility(View.VISIBLE);
                    loadItem();
                    // itemList.clear();
                } else if (!itemType.isEmpty()) {
                    itemid = itemType + " - " + itemBrand;
                    searchitemMerkfilter = db.collection("watchlist").whereEqualTo("type", itemid).get();
                    pbLoading.setVisibility(View.VISIBLE);
                    loadItem();
                    // itemList.clear();

                }
            }
        });
        btnAddItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemQty = etItemQty.getText().toString();
                itemPrice = etItemPrice.getText().toString();
                itemDate = date.getText().toString();
                item = new Item("0", itemid, itemQty, itemPrice, itemDate);
                itemList.add(item);
                adapter = new ItemAdapter(CreateNewReceiptActivity.this, itemList);
                recyclerView.setAdapter(adapter);
                cvDetailItem.setVisibility(View.GONE);
                etItemType.setText("");
                etItemBrand.setText("");
                etItemPrice.setText("");
                etItemQty.setText("");
            }
        });
        btnCheckOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pbLoading.setVisibility(View.VISIBLE);
                Intent i = new Intent(CreateNewReceiptActivity.this,ViewFinalReceiptActivity.class);
                i.putExtra("receiptcart", (Parcelable) itemList);
                startActivity(i);
                cutStock();
            }
        });
    }

    private void loadItem() {
        searchitemMerkfilter
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                                String id = document.getString("id");
                                String date = document.getString("date");
                                String type = document.getString("type");
                                String qty = document.getString("qty");
                                String price = document.getString("price");
                                item = new Item(id, type, qty, price, date);

                            }
                            // adapter = new ItemAdapter(CreateNewReceiptActivity.this, itemList);
                            //recyclerView.setAdapter(adapter);
                            if (!task.getResult().isEmpty()) {
                                pbLoading.setVisibility(View.GONE);
                                tersedia.setVisibility(View.VISIBLE);
                                cvDetailItem.setVisibility(View.VISIBLE);
                            } else if (task.getResult().isEmpty()) {
                                pbLoading.setVisibility(View.GONE);
                                tidakTerdaftar.setVisibility(View.VISIBLE);
                                cvDetailItem.setVisibility(View.GONE);
                            }
                        } else {
                            Log.w(Tag.ITEM, "error getting documents", task.getException());
                            tidakTerdaftar.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

和收据查看代码

public class ViewFinalReceiptActivity extends AppCompatActivity {


    @BindView(R.id.view_final_rc_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.view_final_rc_invoice)
    TextView invoiceNumber;
    @BindView(R.id.view_final_rc_date)
    TextView invoiceDate;
    @BindView(R.id.view_final_rc_btn_print)
    ImageButton btnPrint;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    ItemAdapter adapter;
    Item item;
    List<Item> itemList;
    String type,price,qty,date;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_final_receipt);
        itemList = (List<Item>) getIntent().getParcelableExtra("receiptcart");

       recyclerView.setHasFixedSize(true);
       recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ItemAdapter(this, itemList);
        recyclerView.setAdapter(adapter);
    }
}

4 个答案:

答案 0 :(得分:0)

使用 putParcelableArrayList 代替:

 /**
 * Inserts a List of Parcelable values into the mapping of this Bundle,
 * replacing any existing value for the given key.  Either key or value may
 * be null.
 *
 * @param key a String, or null
 * @param value an ArrayList of Parcelable objects, or null
 */
public void putParcelableArrayList(@Nullable String key,
        @Nullable ArrayList<? extends Parcelable> value) {
    unparcel();
    mMap.put(key, value);
    mFlags &= ~FLAG_HAS_FDS_KNOWN;
}

getParcelableArrayList 获取:

 /**
 * Returns the value associated with the given key, or null if
 * no mapping of the desired type exists for the given key or a null
 * value is explicitly associated with the key.
 *
 * @param key a String, or null
 * @return an ArrayList<T> value, or null
 */
@Nullable
public <T extends Parcelable> ArrayList<T> getParcelableArrayList(@Nullable String key) {
    unparcel();
    Object o = mMap.get(key);
    if (o == null) {
        return null;
    }
    try {
        return (ArrayList<T>) o;
    } catch (ClassCastException e) {
        typeWarning(key, o, "ArrayList", e);
        return null;
    }
}

答案 1 :(得分:0)

尝试 i.putParcelableArrayListExtra("receiptcart", itemList);,然后当您去抓它时ArrayList<Item> newItems = getIntent().getParcelableArrayListExtra("receiptcart");

答案 2 :(得分:0)

我假设List 是Item类的自定义对象的列表。如果是这种情况,则在您的Item类中确保其实现了Serializable:

public class Item implements Serializable{

     . . . . . . 

     <autocreate methods required>

}

通过列表:

myIntent.putExtra("LIST", (Serializable) itemList);
myIntent.startActivity();

要检索其他活动:

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

答案 3 :(得分:0)

使Item实现Parcelable

class Item implements Parcelable{}

通过putParcelableArrayListExtra发送列表:

intent.putParcelableArrayListExtra("key", ArrayList<T extends Parcelable> list);
startActivity(intent);

通过以下方式从第二项活动中获取列表:

getIntent().getParcelableArrayListExtra("key");