无法从购物车安卓工作室中删除项目

时间:2016-09-23 17:51:46

标签: android android-studio shopping-cart

我提到了[this] [1]和[this] [2]网站,并试图根据自己的需要对其进行修改。问题是我无法从购物车中删除商品。我已尝试过一切,包括在stackoverflow和google中搜索解决方案,但没有运气。

这是我的 CatalogActivity.java

    #include <iostream>
using namespace std;

class Distance
{
private:
    const float MTF;
    int feet;
    float inches;
public:
    Distance() : feet(0), inches(0.0), MTF(3.280833F)
    { }
    Distance(float meters) : MTF(3.28033F)
    {
        float fltfeet = MTF * meters;
        feet = int(fltfeet);
        inches = 12*(fltfeet-feet);
    }
    Distance(int ft, float in) : feet(ft), inches(in), MTF(3.280833F)
    { }
    void getdist()
    {
        cout << "\nEnter feet: "; cin >> feet;
        cout << "Enter inches: "; cin >> inches;
    }
    void showdist() const
    { cout << feet << "\'-" << inches << '\"'; }
    operator float() const
    {
        float fracfeet = inches/12;
        fracfeet += static_cast<float>(feet);
        return fracfeet/MTF;
    }

    Distance& operator=(const Distance & otherD)
    {
        feet = otherD.feet;
        inches = otherD.inches;

        return *this;
    }
};
int main()
{
    float mtrs;
    Distance dist1 = 2.35F;
    cout << "\ndist1 = "; dist1.showdist();
    mtrs = static_cast<float>(dist1);

    cout << "\ndist1 = " << mtrs << " meters\n";
    Distance dist2(5, 10.25);
    mtrs = dist2;
    cout << "\ndist2 = " << mtrs << " meters\n";
    Distance dist3; //here is the error 
    dist3 = (Distance)mtrs ;


    //cout<<"\ndist3 = ";dist3.showdist();
    return 0;
}

ShoppingCartHelper.java

package com.comlu.sush.shoppingcart;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;

public class CatalogActivity extends AppCompatActivity {

    private List<Product> mProductList;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_catalog);

        // Obtain a reference to the product catalog
        mProductList = ShoppingCartHelper.getCatalog(getResources());

        // Create the list
        ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
        listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));

        listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
                productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
                startActivity(productDetailsIntent);
            }
        });

        Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
        viewShoppingCart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
                startActivity(viewShoppingCartIntent);
            }
        });

    }
}

ShoppingCartActiity.java

package com.comlu.sush.shoppingcart;   
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector; 

public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();

    public static List<Product> getCatalog(Resources res){
        if(catalog == null) {
            catalog = new Vector<Product>();
            catalog.add(new Product("Dead or Alive", res
                    .getDrawable(R.drawable.first),
                    "Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
            catalog.add(new Product("Switch", res
                    .getDrawable(R.drawable.second),
                    "Switch by Chip Heath and Dan Heath", 24.99));
            catalog.add(new Product("Watchmen", res
                    .getDrawable(R.drawable.third),
                    "Watchmen by Alan Moore and Dave Gibbons", 14.99));
        }

        return catalog;
    }

    public static void setQuantity(Product product, int quantity) {
        // Get the current cart entry
        ShoppingCartEntry curEntry = cartMap.get(product);

        // If the quantity is zero or less, remove the products
        if(quantity <= 0) {
            if(curEntry != null)
                removeProduct(product);
            return;
        }

        // If a current cart entry doesn't exist, create one
        if(curEntry == null) {
            curEntry = new ShoppingCartEntry(product, quantity);
            cartMap.put(product, curEntry);
            return;
        }

        // Update the quantity
        curEntry.setQuantity(quantity);
    }

    public static int getProductQuantity(Product product) {
        // Get the current cart entry
        ShoppingCartEntry curEntry = cartMap.get(product);

        if(curEntry != null)
            return curEntry.getQuantity();

        return 0;
    }

    public static void removeProduct(Product product) {
        cartMap.remove(product);
    }

    public static List<Product> getCartList() {
        List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
        for(Product p : cartMap.keySet()) {
            cartList.add(p);
        }

        return cartList;
    }
}

ProductDetailsActivity.java

package com.comlu.sush.shoppingcart;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity {

    private List<Product> mCartList;
    private ProductAdapter mProductAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        mCartList = ShoppingCartHelper.getCartList();

        // Make sure to clear the selections
        for(int i=0; i<mCartList.size(); i++) {
            mCartList.get(i).selected = false;
        }

        // Create the list
        final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
        mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
        listViewCatalog.setAdapter(mProductAdapter);

        listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                mProductAdapter.toggleSelection(position);

            }
        });

        removeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mProductAdapter.removeSelected();
        }
    });
}

    @Override
    protected void onResume() {
        super.onResume();

        // Refresh the data
        if(mProductAdapter != null) {
            mProductAdapter.notifyDataSetChanged();
        }
    }

}

ProductAdapter.java

package com.comlu.sush.shoppingcart;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class ProductDetailsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);

        final int result=0;

        List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());

        int productIndex = getIntent().getExtras().getInt(
                ShoppingCartHelper.PRODUCT_INDEX);
        final Product selectedProduct = catalog.get(productIndex);

        // Set the proper image and text
        ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
        productImageView.setImageDrawable(selectedProduct.productImage);
        TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
        productTitleTextView.setText(selectedProduct.title);
        TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
        productDetailsTextView.setText(selectedProduct.description);

        // Update the current quantity in the cart
        TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
        textViewCurrentQuantity.setText("Currently in Cart: "
                + ShoppingCartHelper.getProductQuantity(selectedProduct));


        // Save a reference to the quantity edit text
        final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);

        Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
        addToCartButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // Check to see that a valid quantity was entered
                int quantity = 0;
                try {
                    quantity = Integer.parseInt(editTextQuantity.getText()
                            .toString());

                    if (quantity < 0) {
                        Toast.makeText(getBaseContext(),
                                "Please enter a quantity of 0 or higher",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                } catch (Exception e) {
                    Toast.makeText(getBaseContext(),
                            "Please enter a numeric quantity",
                            Toast.LENGTH_SHORT).show();

                    return;
                }

                // If we make it here, a valid quantity was entered
                ShoppingCartHelper.setQuantity(selectedProduct, quantity);

                // Close the activity
                finish();
            }
        });

    }

}

2 个答案:

答案 0 :(得分:0)

您应该将数据操作移动到适配器,并且在设计方面它会有意义并且还可以解决您告诉我们的问题。

ProductAdapter

中写下此方法
public void removeSelected() {
    for(int i = mProductList.size()-1; i >= 0; i--) {
        if(mProductList.get(i).selected) {
             mProductList.remove(i);
        }
    }
    notifyDataSetChanged();
}

更新您的OnClickListener(当然是ShoppingCartActiity):

removeButton.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
         mProductAdapter.removeSelected();
     }
});

修改

我注意到你并没有在这里应用OOP的封装概念。也就是说,ShoppingCartActiity不应该对属于您的适配器的数据进行更改。

因此,只需在public内为ProductAdapter创建ShoppingCartActiity方法,然后根据需要从ProductAdapter调用它们。

  1. public void toggleSelection(int position) { Product selectedProduct = (Product) getItem(position); if(selectedProduct.selected) { // no need to check " == true" selectedProduct.selected = false; } else { selectedProduct.selected = true; } notifyDataSetInvalidated(); }

    中复制此方法
    mProductAdapter.toggleSelection(position);
  2. ShoppingCartActiity将替换以下代码Product selectedProduct = mCartList.get(position); if(selectedProduct.selected == true) selectedProduct.selected = false; else selectedProduct.selected = true; mProductAdapter.notifyDataSetInvalidated();

    ShoppingCartActiity
  3. EDIT2

    问题是ShoppingCartEntry在启动时从removeButton获取项目,但在删除项目时它永远不会将更改写回。

    1. 将您的onClick() mProductAdapter.removeSelected(); if (product.selected) { // set products which are remaining in the adapter ShoppingCartHelper.setProducts(mProductAdapter.getProducts()); } 更新为:

      ShoppingCartHelper.setProducts()
    2. public static void setProducts(ArrayList<Product> products) { catalog = new Vector<Product>(); for (Product product : products) { catalog.add(product); } } 将使用传递的数据替换旧数据:

      mProductAdapter.getProducts()
    3. Product只会返回public List<Product> getProducts() { return mProductList; } 的列表,例如:

      readAll()

答案 1 :(得分:0)

您只需要从列表中删除所选项目,然后在adapter.notifiyDataSetChanged()之后刷新适配器。

removeButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Loop through and remove all the products that are selected
                    // Loop backwards so that the remove works correctly
                    for(int i=mCartList.size()-1; i>=0; i--) {

                        if(mCartList.get(i).selected) {
                            mCartList.remove(i);
                            //mProductAdapter.removeSelected();
                        }
                    }
                  if(mProductAdapter!=null)
                    mProductAdapter.notifyDataSetChanged();

                }
            });