首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试在Android中复制不同列表中的对象

尝试在Android中复制不同列表中的对象
EN

Stack Overflow用户
提问于 2015-06-26 12:44:33
回答 1查看 1.2K关注 0票数 0

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

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

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

按部件划分我的代码:

1.解析来自服务器的产品的方法:

代码语言:javascript
运行
复制
/**
     * 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.在产品网格中显示产品的方法:

代码语言:javascript
运行
复制
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.捕捉拖放购物车上的侦听器:

代码语言:javascript
运行
复制
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.向购物车添加新产品的方法:

代码语言:javascript
运行
复制
/**
     * 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.这是我的模型:

代码语言:javascript
运行
复制
@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;
...
}

问题是,当我在购物车中删除一个产品时,我也要在product中删除这个对象:(我希望处理两个列表中的不同实例。

copyToRealm方法究竟是如何工作的?我真的在处理这个物体的副本吗?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-26 14:03:42

我解决了我的问题。当我将产品从product添加到购物车时,我需要在添加它之前使用"createObject“。

代码语言:javascript
运行
复制
ProductRealm pRealm = Global.REALM.createObject(ProductRealm.class);

我的失败:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31073513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档