我有两个模型,第一个是有 HashMap < String, ProductOption> 的 cartItem 模型,ProductOption 是第二个模型。
第一个模型:
public class CartItem extends BaseObservable implements Serializable {
...
HashMap<String, ProductOption> options;
...
@Ignore
public HashMap<String, ProductOption> getOptions() {
return options;
}
@Ignore
public void setOptions(HashMap<String, ProductOption> options) {
this.options = options;
}
}
第二个模型:
public class ProductOption implements Parcelable {
String optionId;
String optionKey;
String optionValue;}
当我尝试将购物车项目列表设置到 recyclerview 适配器时,所有 cartitem 模型项目都会复制,但选项会复制为 null
mViewModel.getCartItems().observe(this,cartItems -> {
if (FirebaseAuth.getInstance().getCurrentUser() == null) return;
if (cartItems ==null ) return;
cartItemList = cartItems;
cartAdapter.setCartItemList(cartItems);
});
感谢您的帮助。
最佳答案
我发现使选项为空的原因是我通过迭代器循环选项变量并使用 it.remove() 这种循环删除 cartItemList 上的选项的方式
if (cartItemList.get(i).getOptions() != null){
HashMap<String, ProductOption> optionHashMap = cartItemList.get(i).getOptions();
Iterator it = optionHashMap.entrySet().iterator();
double optionPrice = 0;
while (it.hasNext()){
Map.Entry pair = (Map.Entry) it.next();
optionPrice += Double.valueOf(((ProductOption)pair.getValue()).getOptionValue());
it.remove();
}
price = price + optionPrice;
}
关于java - Hashmap返回空值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58042828/