如何获得总计的片段

如何解决如何获得总计的片段

请帮助我,我正面临这些问题,并且花了更多时间来解决这些问题,但是他们打电话给多友陪伴,所以请显示视频并建议我找出并解决问题。它是一个简单的杂货店应用程序为了帮助检查我的知识,请提供帮助并有可能分享另一种快速获得我解决方案的快速方法...感谢社区的支持..

my output link

i want similer to these in fragmnet

我的购物车片段代码

    public class CartFragment extends Fragment implements UpdateInf{
    
        RecyclerView cartList;
       // public static List<ProductModel> cartModels;
        private List<ProductModel> cartItemList;
        public static TextView tvTotalWithCheckout;
        CartHelper cartHelper;
        public static double grandTotalPlus = 0.0d;
        int cartCount;
        ProductModel productModel;
        UpdateInf updateInf;
    
        public CartFragment() {
    
        }
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_cart,container,false);
            cartList = view.findViewById(R.id.cartList);
            tvTotalWithCheckout = view.findViewById(R.id.tvTotalWithCheckout);
            cartHelper = new CartHelper(getActivity());
            productModel = new ProductModel();
            updateInf = this;
    
    
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            cartList.setLayoutManager(linearLayoutManager);
    
    
    
            //LayoutAnimationController layoutAnimationController = AnimationUtils.loadLayoutAnimation(getActivity(),R.anim.layout_anim_right_to_left);
           // cartList.getAdapter().notifyDataSetChanged();
           // cartList.setLayoutAnimation(layoutAnimationController);
            //cartList.scheduleLayoutAnimation();
    
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL);
            cartList.addItemDecoration(dividerItemDecoration);
    
    
            cartItemList = cartHelper.getAllProducts();
    
            MyCartAdapter myCartAdapter = new MyCartAdapter(getActivity(),cartItemList,updateInf);
            cartList.setAdapter(myCartAdapter);
    
           // tvTotalWithCheckout.setText( "\u20B9" + grandTotal(cartItemList));
            Log.e("grandCheckTotal","setMyCartItem: "+grandTotalPlus);
    
            tvTotalWithCheckout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(),CheckoutActivity.class);
                    startActivity(intent);
                }
            });
    
            return view;
        }
    
        @Override
        public void setQuantity(int quantity) {
            grandTotal(cartItemList);
            Log.e("grandTotal","setQuantity: "+ grandTotalPlus);
        }
    
        private double grandTotal(List<ProductModel> cartItemList) {
            for (ProductModel model : cartItemList) {
               // Log.e("cartData","setMyCartItem: " + model.getProductId() + ":" + model.getProductName());
                cartCount = model.getProductQty();
                grandTotalPlus += Double.parseDouble(model.getProductPrice()) * cartCount;
            }
            return grandTotalPlus;
        }
    
    
    
    }


**my adapter code**


public class MyCartAdapter extends RecyclerView.Adapter<MyCartAdapter.Holder> {

    private Context context;
    private List<ProductModel> productModels;
    CartHelper cartHelper;
    ProductModel productModel;
    UpdateInf updateInf;


    public MyCartAdapter(Context context,List<ProductModel> productModels,UpdateInf updateInf) {
        this.context = context;
        this.productModels = productModels;
        cartHelper = new CartHelper(context);
        this.updateInf = updateInf;
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cart_items,parent,false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final Holder holder,final int position) {

        productModel = productModels.get(position);
        Glide.with(context).load(productModels.get(position).getProductImage()).into(holder.cartImgProduct);
        holder.tvProductName.setText(productModels.get(position).getProductName());
        holder.tvProductPrice.setText("\u20B9" + productModels.get(position).getProductPrice());
        holder.tvProductType.setText(productModels.get(position).getProductType());
        holder.tvQty.setText(String.valueOf(productModels.get(position).getProductQty()));


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

                //grandTotalPlus = 0.0d;

                int cartIncrementItem = productModels.get(position).getProductQty();
                cartIncrementItem += 1;

                productModels.get(position).setProductQty(cartIncrementItem);
//                double cash = Double.parseDouble(productModels.get(position).getProductPrice()) * productModels.get(position).getProductQty();

                holder.tvQty.setText(String.valueOf(productModels.get(position).getProductQty()));

//                productModels.get(position).setTotalCash(cash);
                cartHelper.updateCart(new ProductModel(productModels.get(position).getProductId(),productModels.get(position).getProductQty()));
                updateInf.setQuantity(cartIncrementItem);


            }
        });

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

                    int cartDecrementItem = productModels.get(position).getProductQty();

                    if (cartDecrementItem == 1) {

                    } else {
                        cartDecrementItem -= 1;
                        productModels.get(position).setProductQty(cartDecrementItem);
                        holder.tvQty.setText(String.valueOf(productModels.get(position).getProductQty()));
                        updateInf.setQuantity(cartDecrementItem);

                }
                cartHelper.updateCart(new ProductModel(productModels.get(position).getProductId(),productModels.get(position).getProductQty()));
            }
        });


    }


    @Override
    public int getItemCount() {
        return productModels.size();
    }

    class Holder extends RecyclerView.ViewHolder {

        ImageView cartImgProduct,imgRemoveCart,imgIncrement,imgDecrement;
        TextView tvProductName,tvProductPrice,tvProductType,tvQty;

        public Holder(@NonNull View itemView) {
            super(itemView);

            cartImgProduct = itemView.findViewById(R.id.cartImgProduct);
            tvProductName = itemView.findViewById(R.id.tvProductName);
            tvProductPrice = itemView.findViewById(R.id.tvProductPrice);
            tvProductType = itemView.findViewById(R.id.tvProductType);
            imgIncrement = itemView.findViewById(R.id.imgIncrement);
            imgDecrement = itemView.findViewById(R.id.imgDecrement);
            tvQty = itemView.findViewById(R.id.tvQty);

        }
    }

}

我的购物车帮助代码

public class CartHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "grocery_store";
    private static final String TABLE_CART = "cart";
    private static final String KEY_PRODUCT_ID = "product_id";
    private static final String KEY_PRODUCT_NAME = "product_name";
    private static final String KEY_PRODUCT_PRICE = "product_price";
    private static final String KEY_PRODUCT_TYPE = "product_type";
    private static final String KEY_PRODUCT_IMAGE = "product_image";
    private static final String KEY_PRODUCT_QTY = "product_qty";
    private static final String KEY_TOTAL_CASH = "total_cash";


    public CartHelper(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_CART_TABLE =
                "CREATE TABLE " + TABLE_CART + "(" + KEY_PRODUCT_ID + " TEXT PRIMARY KEY,"
                        + KEY_PRODUCT_NAME + " TEXT,"
                        + KEY_PRODUCT_PRICE + " TEXT,"
                        + KEY_PRODUCT_TYPE + " TEXT,"
                        + KEY_PRODUCT_IMAGE + " TEXT,"
                        + KEY_PRODUCT_QTY + " INTEGER" + ")";

        db.execSQL(CREATE_CART_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CART);
        onCreate(db);
    }

    public void addToCart(ProductModel productModels) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_PRODUCT_ID,productModels.getProductId());
        contentValues.put(KEY_PRODUCT_NAME,productModels.getProductName());
        contentValues.put(KEY_PRODUCT_PRICE,productModels.getProductPrice());
        contentValues.put(KEY_PRODUCT_TYPE,productModels.getProductType());
        contentValues.put(KEY_PRODUCT_IMAGE,productModels.getProductImage());
        contentValues.put(KEY_PRODUCT_QTY,productModels.getProductQty());


        sqLiteDatabase.insert(TABLE_CART,contentValues);
        sqLiteDatabase.close();
    }

    public List<ProductModel> getAllProducts() {

        List<ProductModel> productModelList = new ArrayList<ProductModel>();

        String query = "SELECT * FROM " + TABLE_CART;

        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery(query,null);

        if (cursor.moveToFirst()) {
            do {
                ProductModel productModel = new ProductModel();
                productModel.setProductId(cursor.getString(0));
                productModel.setProductName(cursor.getString(1));
                productModel.setProductPrice(cursor.getString(2));
                productModel.setProductType(cursor.getString(3));
                productModel.setProductImage(cursor.getString(4));
                productModel.setProductQty(cursor.getInt(5));


                productModelList.add(productModel);
            } while (cursor.moveToNext());
        }

        return productModelList;
    }

    public int updateCart(ProductModel productModel) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PRODUCT_QTY,productModel.getProductQty());
        //values.put(KEY_TOTAL_CASH,productModel.getTotalCash());
        //values.put(KEY_PRODUCT_PRICE,productModel.getProductPrice());

        // updating row
        return db.update(TABLE_CART,values,KEY_PRODUCT_ID + " = ? ",new String[]{String.valueOf(productModel.getProductId())});
    }

    // Deleting single contact
    public void deleteCart(ProductModel productModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CART,KEY_PRODUCT_ID + " = ?",new String[]{String.valueOf(productModel.getProductId())});
        db.close();
    }

}

解决方法

private double grandTotal(List<ProductModel> cartItemList) {
            grandTotalPlus = 0.0d // Reinitialze to zero
            for (ProductModel model : cartItemList) {
               // Log.e("cartData","setMyCartItem: " + model.getProductId() + ":" + model.getProductName());
                cartCount = model.getProductQty();
                grandTotalPlus += Double.parseDouble(model.getProductPrice()) * cartCount;
            }
            return grandTotalPlus;
        }

grandtotalplus是一个静态变量,当您离开页面时,它的值永远不会重置,因此,第一次访问购物车页面时,它的值是50。之后,当您返回并添加更多商品,然后返回购物车页面时,它仍然具有值50,您便开始添加它。这就是为什么你要135。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-