Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • how to add a product into cart shopify ?

    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 572
    Comment on it

    In our previous blog we read about categories and their products now we ll look how to add each product into cart for checkout.

    Each product has a unique id and product varients that we ll add into cart.

    This is the basic method we uses to add cart :

    Suppose we hava a product list and on click or any product list item we ll send product varient and activity context to this method like this :

    product list view cart icon like and arraylist is same like we had in our previous blog:
    llAddCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {SampleApplication.addToCart(mArrayList.get(pos).getVariants().get(0), true, ProductsListActivity.this);
        }
    });

    Now method to add cart :

    public static void addToCart(ProductVariant aProductVariant,boolean from,Activity aActivity){
    
        Cart cart = AppSharedPrefrences.getCart(aActivity);
        if (cart == null){
            cart = new Cart();
            AppLogs.printLogs("cart :", " is :" + " null ");
        }
    
        cart.addVariant(aProductVariant);
        AppSharedPrefrences.saveCart(cart, aActivity);
    
        if (from)
         Toast.makeText(aActivity,"Item Added in cart",Toast.LENGTH_SHORT).show();
    
    }

     

    Create a class named AppsharedPreference to save cart locally :

    
    public static void saveCart(Cart aCart,Activity aActivity){
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(aActivity);
        mEditor= mSharedPreferences.edit();
        mGson = new Gson();
        String json = mGson.toJson(aCart);
        mEditor.putString(key_cart_info, json);
        mEditor.commit();
    }
    
    public static Cart getCart(Activity aActivity){
        mGson = new Gson();
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(aActivity);
        String json = mSharedPreferences.getString(key_cart_info, "");
        Cart cart = mGson.fromJson(json, Cart.class);
        return cart;
    }

    Note : you can't maintain cart globally or you can't sync with web because shopify doesn't maintain cart so you have to store it locally.

    In our next tutorial we ll learn about shipping address of customer before checkout.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: