尝试使用Android中的Realm复制不同列表中的对象

时间:2015-06-26 12:44:33

标签: android realm

我在Realm的Android应用程序中工作,当我尝试管理不同列表(Shooping Cart和Products Grid)中的对象时,我遇到了问题。 在产品网格中,我显示从服务器解析的产品,然后将这些产品拖放到购物车上以创建要购买的产品列表。

当我在对象上使用方法“copyToRealm”并尝试在其中一个列表中修改它时,两个列表的对象也会被修改。

我尝试在添加到两个列表之前复制,但似乎对象始终是相同的。

我的部分代码:

1。从服务器解析产品的方法:

/**
     * Parse products got from server
     * @param result
     */
    public static void parseProducts(Realm realm, String result){
        Logs.MessageLogs("parseProducts", result, "v", Global.SHOW_LOGS);
        Object product = null;
        JSONObject json = null;
        ProductRealm pRealm, pObject;

        try {
            json = new JSONObject(result);

            if(Global.USER_LOGGED.getProductsGrid().size() > 0)
                _CRUDDatabase.clearProductsGrid(realm);

            for (Iterator<?> iterator = json.keys(); iterator.hasNext(); ) {
                String key = (String) iterator.next();
                if (json.get(key) instanceof JSONObject) {    //Category with children
                    product = ((JSONObject) json.get(key));

                    realm.beginTransaction();
                    pObject = realm.createObject(ProductRealm.class);
                    pRealm  = _CRUDDatabase.createNewProduct(Global.PREVIOUS_CATEGORY.getId(), product);
                    pObject = realm.copyToRealm(pRealm);                 //copy value to Realm
                    Global.USER_LOGGED.getProductsGrid().add(pObject);   //add value to RealmList
                    realm.commitTransaction();
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception ex){
            ex.printStackTrace();
        }
    }

2。在产品网格中显示产品的方法:

private void initializeGridView(View view){
//        int width = Utility.getScreenDimension((Activity) getActivity(), "WIDTH");

        mGridView = (RecyclerView) view.findViewById(R.id.RecyclerView);
        mGridView.setHasFixedSize(true);
        mShopGridViewAdapter = new ShopGridViewAdapter(getActivity(), productList);
        mShopGridViewAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Item", "Clicked on item: " + mGridView.getChildAdapterPosition(v));

                ProductRealm pRealm = productList.get(mGridView.getChildAdapterPosition(v));
                UtilityDB.resetValuesToDefault(Global.REALM, pRealm);
                openProductDetailFragment(fm, pRealm);
            }
        });

        mGridView.setAdapter(mShopGridViewAdapter);
        mGridView.setLayoutManager(new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false));

        //Item Decoration
        mGridView.setItemAnimator(new DefaultItemAnimator());
}

第3。听众捕捉拖放购物车:

public class ShoppingCartDragListener implements View.OnDragListener {
...

    private void checkTypeOfDraggedProduct(ProductRealm pRealm) {
            ShopGridViewFragment sgv;

            if(pRealm.getTypeId().equals(TAG_CONFIGURABLE)){ //Configurable product
                sgv = new ShopGridViewFragment();
                sgv.openProductDetailFragment(fm, pRealm);

            } else {    //Simple product
                pRealm.setQuantity(1);   //Only increment 1 unit when drag to shopping cart
                int pos = _CRUDDatabase.addNewProductToCart(Global.REALM, pRealm);
                shoppingCartAdapter.notifyItemInserted(pos);
                ShoppingCartFragment.updateStatusCart();
            }
        }
...
}

4。将新产品添加到购物车的方法:

/**
     * Add new product to Shopping Cart from single productItem
     * @param realm
     * @param pObject
     * @return
     */
    public static int addNewProductToCart(Realm realm, ProductRealm pObject) {
        int pos = -1;
        ProductRealm pRealmDatabase = readProductFromDatabase(realm, pObject.getEntityId());


        realm.beginTransaction();
        if(pRealmDatabase != null){     //Update product in shopping cart
            pos = UtilityDB.getProductPositionIntoCart(pObject);
            if(pos != -1) {
                Global.USER_LOGGED.getCart().getProducts().get(pos).setQuantity(pObject.getQuantity() + pRealmDatabase.getQuantity());
                Global.USER_LOGGED.getCart().getProducts().get(pos).setQuantityWeight(pObject.getQuantityWeight() + pRealmDatabase.getQuantityWeight());
            }

        } else {    //Add new product to cart
            //ProductRealm pRealm = realm.copyToRealm(pObject);
            pObject.setIsIntoShoppingCart(true);
            Global.USER_LOGGED.getCart().getProducts().add(pObject);
        }
        Global.USER_LOGGED.getCart().setLastUpdate(Utility.getCurrentDateTime());
        realm.commitTransaction();

        return pos;
    }

5。这是我的模特:

@RealmClass
public class UserRealm extends RealmObject implements Serializable {

    private String    email;
    private String    password;
    private String    tokenId;
    private String    tokenSecret;
    private String    creationDate;
    private RealmList<ProductRealm> productsGrid;   //Temp table to load category products
    private CartRealm cart;        //One-to-one relationship
...
}

@RealmClass
public class CartRealm extends RealmObject implements Serializable {

    private String creationDate;
    private String lastUpdate;
    private int    totalDinitos;
    private float  totalPrice;
    private RealmList<ProductRealm> products;
...
}

@RealmClass
public class ProductRealm extends RealmObject implements Serializable {

    private String  catId;   //Only one category per product. In generic case many category per product
    private String  entityId;
    private String  parentId;
    private String  typeId;
    private String  sku;
    private String  canaryProduct;
    private String  premium;
    private String  brand;
    private String  dinitosQty;
    private String  name;
    private String  ean;
    private String  description;
    private String  shortDescription;
    private String  attributeSet;
    private String  weight;
    private String  isSaleable;
    private String  imageUrl;
    private String  unit;
    private String  unitFresh;
    private String  childrenSelected;
    private float   price;
    private float   minWeight;
    private float   quantityWeight;
    private int     quantity;
    private int     stock;
    private int     typeOfAttribute;    //0: Per units | 1: Per weight
    private boolean isIntoShoppingCart; //Flag to indicate if the product is into the Shopping Cart
    private RealmList<AttributeRealm> attributeItems;
    private RealmList<ProductRealm>   children;
...
}

问题是,当我在购物车中删除产品时,我也在产品网格中删除此对象:( 我想在两个列表中使用不同的实例。

如何正确处理copyToRealm方法?我真的在使用该对象的副本吗?

我希望你能帮助我:) 提前致谢

1 个答案:

答案 0 :(得分:1)

我解决了我的问题。当我将产品网格中的产品添加到购物车时,我需要&#34; createObject&#34;之前添加它。

ProductRealm pRealm = Global.REALM.createObject(ProductRealm.class);

我的失败:)