Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法从购物车android studio中删除项目_Android_Android Studio_Shopping Cart - Fatal编程技术网

无法从购物车android studio中删除项目

无法从购物车android studio中删除项目,android,android-studio,shopping-cart,Android,Android Studio,Shopping Cart,我参考了[this][1]和[this][2]网站,并试图根据自己的需要对其进行修改。问题是我无法从购物车中删除项目。我尝试了一切,包括在stackoverflow和google中搜索解决方案,但没有成功 这是我的CatalogActivity.java package com.comlu.sush.shoppingcart; import android.content.Intent; import android.os.Bundle; import android.support.v7.a

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

这是我的CatalogActivity.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);
            }
        });

    }
}
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();
        }
    }

}
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();
            }
        });

    }

}
package com.comlu.sush.shoppingcart;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class ProductAdapter extends BaseAdapter {

    private List<Product> mProductList;
    private LayoutInflater mInflater;
    private boolean mShowQuantity;
    private boolean mShowCheckbox;

    public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
        mProductList = list;
        mInflater = inflater;
        mShowQuantity = showQuantity;
        mShowCheckbox = showCheckbox;
    }

    @Override
    public int getCount() {
        return mProductList.size();
    }

    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewItem item;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item, null);
            item = new ViewItem();

            item.productImageView = (ImageView) convertView
                    .findViewById(R.id.ImageViewItem);

            item.productTitle = (TextView) convertView
                    .findViewById(R.id.TextViewItem);

            item.productQuantity = (TextView) convertView
                    .findViewById(R.id.textViewQuantity);

            item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);

            convertView.setTag(item);
        } else {
            item = (ViewItem) convertView.getTag();
        }

        Product curProduct = mProductList.get(position);

        item.productImageView.setImageDrawable(curProduct.productImage);
        item.productTitle.setText(curProduct.title);

        if(!mShowCheckbox) {
            item.productCheckbox.setVisibility(View.GONE);
        } else {
            if(curProduct.selected == true)
                item.productCheckbox.setChecked(true);
            else
                item.productCheckbox.setChecked(false);
        }

        // Show the quantity in the cart or not
        if (mShowQuantity) {
            item.productQuantity.setText("Quantity: "
                    + ShoppingCartHelper.getProductQuantity(curProduct));
        } else {
            // Hid the view
            item.productQuantity.setVisibility(View.GONE);
        }

        return convertView;
    }
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();
}
public void removeSelected() {
        for(int i=mProductList.size()-1; i>=0; i--) {
            if(mProductList.get(i).selected) {
                mProductList.remove(i);
            }
        }
        notifyDataSetChanged();
    }
    private class ViewItem {
        ImageView productImageView;
        TextView productTitle;
        TextView productQuantity;
        CheckBox productCheckbox;
    }
}
package com.comlu.sush.shoppingcart;
导入android.content.Intent;
导入android.os.Bundle;
导入android.support.v7.app.AppActivity;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.AdapterView;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.AdapterView.OnItemClickListener;
导入java.util.List;
公共类CatalogActivity扩展了AppCompatActivity{
私人名单;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_目录);
//获取对产品目录的引用
MPProductList=ShoppingCartHelper.getCatalog(getResources());
//创建列表
ListView listViewCatalog=(ListView)findViewById(R.id.listViewCatalog);
setAdapter(新产品适配器(MPProductList,GetLayoutFlater(),false,false));
setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父视图、视图、整型位置、,
长id){
Intent ProductDetailsInt=新的Intent(getBaseContext(),ProductDetailsActivity.class);
ProductDetailsInt.putExtra(ShoppingCartHelper.PRODUCT\u索引,位置);
startActivity(产品详细信息);
}
});
按钮viewShoppingCart=(按钮)findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent viewShoppingCartIntent=新意图(getBaseContext(),ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
ShoppingCartHelper.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;
    }
}
package com.comlu.sush.shoppingcart;
导入android.content.res.Resources;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入java.util.Vector;
公共类购物助手{
公共静态最终字符串PRODUCT\u INDEX=“PRODUCT\u INDEX”;
私有静态列表目录;
私有静态映射cartMap=newhashmap();
公共静态列表getCatalog(资源资源){
if(catalog==null){
catalog=新向量();
目录。添加(新产品(“死或活”,res
.getDrawable(R.drawable.first),
《汤姆·克兰西与格兰特·布莱克伍德的生死抉择》,29.99);
目录.添加(新产品(“开关”),res
.getDrawable(R.drawable.second),
“Chip Heath和Dan Heath切换”,24.99);
目录.添加(新产品(“看守人”),第
.getDrawable(R.drawable.third),
“艾伦·摩尔和戴夫·吉本斯的守望者”,14.99);
}
退货目录;
}
公共静态无效设置数量(产品、整数数量){
//获取当前购物车条目
ShoppingCarentry curEntry=cartMap.get(产品);
//如果数量为零或更少,则移除产品

如果(quantity您应该将数据操作移动到适配器,并且从设计角度来看,这是有意义的,并且可能会解决您告诉我们的问题

ProductAdapter
中编写此方法:

public void removeSelected() {
    for(int i = mProductList.size()-1; i >= 0; i--) {
        if(mProductList.get(i).selected) {
             mProductList.remove(i);
        }
    }
    notifyDataSetChanged();
}
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();
}
更新您的
OnClickListener
(当然是在您的
购物活动中):

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

因此,只需在
ProductAdapter
中为要选择的项目创建
public
方法,然后根据需要从
shoppingcartactity
调用它们

  • 将此方法复制到
    产品适配器中

    public void removeSelected() {
        for(int i = mProductList.size()-1; i >= 0; i--) {
            if(mProductList.get(i).selected) {
                 mProductList.remove(i);
            }
        }
        notifyDataSetChanged();
    }
    
    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();
    }
    
  • MPProductAdapter.切换选择(位置);
    将替换以下代码
    ShoppingCartActivity

    Product selectedProduct = mCartList.get(position);
    if(selectedProduct.selected == true)
        selectedProduct.selected = false;
    else
        selectedProduct.selected = true;
    
    mProductAdapter.notifyDataSetInvalidated();
    
  • 编辑2 问题在于,
    shoppingcartactity
    在启动时从
    shoppingcarentry
    获取项目,但在删除项目时,它从不回写对它的更改

  • removeButton
    onClick()
    更新为:

    mProductAdapter.removeSelected();
    if (product.selected) {
        // set products which are remaining in the adapter
        ShoppingCartHelper.setProducts(mProductAdapter.getProducts());
    }
    
  • ShoppingCartHelper.setProducts()
    将用传递的数据替换旧数据:

    public static void setProducts(ArrayList<Product> products) {
        catalog = new Vector<Product>();
        for (Product product : products) {
            catalog.add(product);
        }
    }
    

  • 您只需从列表中删除所选项目,在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();
    
                    }
                });
    

    请包括您的日志。可能是@AdityaVyas Lakhan的副本。感谢您花时间发表评论。您建议我怎么做才能使这项工作成功?我是这方面的初学者,所以我不知道我应该做什么。@AdityaVyas Lakhan您的链接不符合我的要求。发生的错误是在我尝试了一些新的东西之后。我的应用程序是already工作正常,这不是我在问题中提到的错误。该项目已从我的购物车中删除,但当我第二次查看它时,它又在那里。这是我的问题。如果它崩溃,必须有日志猫。应用packagename和日志级别(警告、错误等)过滤器。非常感谢您发布此代码。我尝试了此操作,但它给了我一个JavaNullPointerException。
    然后按按钮调用:
    。您的意思是在ShoppingCartActivity的按钮中,对吗?我已根据您的建议更新了我的代码。请提供一个解决方案。@Sushant首先您正在这样做