简体   繁体   English

如何计算购物车中的总价?

[英]How do I calculate the total price in the shopping cart?

The shopping cart section of my app is implemented offline when the user presses the add button.当用户按下添加按钮时,我的应用程序的购物车部分是离线实现的。 The product is stored in the database and then displayed in the shopping cart.产品存储在数据库中,然后显示在购物车中。

my question我的问题

How can I change the price of products after changing the numberpicker of products?(The total price of a number is calculated from each product, but after changing the number, the total price does not change.)更改商品编号后如何更改商品价格?(一个编号的总价是从每个商品计算出来的,但更改编号后,总价不变。)

cartadapter.java cartadapter.java

public class FacultyAdapter extends RecyclerView.Adapter<FacultyAdapter.FacultyViewHolder> {

dbhandler mydb;
private int counter=1;
private Context context;
private List<Faculty> facultyList;
Faculty faculty ;

public FacultyAdapter(Context context, List<Faculty> facultyList) {
    this.context = context;
    this.facultyList=facultyList;
}

@NonNull
@Override
public FacultyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(context).inflate(R.layout.itemcard,parent,false);
    RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 
   ViewGroup.LayoutParams.WRAP_CONTENT);
    view.setLayoutParams(lp);

    return new FacultyViewHolder(view);
}


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

     faculty = facultyList.get(position);
    holder.title.setText(faculty.getName());
   holder.price.setText(faculty.getPrice());
   holder.count.setText(String.valueOf(faculty.getQty()));
   holder.inc.setGravity(Gravity.CENTER);
    String photoname=faculty.getImage();
    Glide
            .with(context)
            .load( Urls.image+photoname)
            .placeholder(R.mipmap.ic_launcher_round)
            .error(R.drawable.logo)
           .into(holder.img);

    mydb=new dbhandler(context);


         //////////////////////////////////
    holder.inc.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           int count= Integer.parseInt(String.valueOf(holder.count.getText()));
           count++;
           holder.count.setText(String.valueOf(count));
            faculty.setQty(count);
        Log.d("inc",""+faculty.getQty());
       }
   });
    holder.dec.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int count= Integer.parseInt(String.valueOf(holder.count.getText()));
            if(count>1){
                count--;
                holder.count.setText(String.valueOf(count));
                faculty.setQty(count);
              //  Log.d("dec",""+count);
            }
        }
    });
}
 ///////////////////////////////////
@Override
public int getItemCount() {
    return facultyList.size();
}
 ////////////////////////////////
public class FacultyViewHolder extends RecyclerView.ViewHolder {

    TextView title;
    TextView price,count;
   ImageView img;
    CardView card,viewBackground;

 Button inc,dec;
    private FacultyViewHolder(View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.txt_list_item_title);
        price = itemView.findViewById(R.id.txt_list_item_des);  
       img=itemView.findViewById(R.id.image_cart);
        inc=itemView.findViewById(R.id.increment);
        dec=itemView.findViewById(R.id.decrement);
        count=itemView.findViewById(R.id.display);
        card =itemView.findViewById(R.id.card);
        viewBackground =itemView.findViewById(R.id.view_background);
    }
}

//////////////////////////////////////////
public void remove(int position){
    final Faculty s = facultyList.get(position);
    facultyList.remove(position);
    String e=s.getId().toString();
    mydb.delete(e);
    notifyItemRemoved(position);
}

} }

cartactivity.java cartactivity.java

 public class cart extends AppCompatActivity implements 
  RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {
Button Add,total; 
ImageButton back_btn;
Faculty items;
private TextView price_total; 
FacultyAdapter facultyAdapter;
dbhandler mydb;
String name;
 List<Faculty> posts;
String id, title, status, price, image,sum;
@SuppressLint("WrongConstant")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);

    RecyclerView recyclerView = findViewById(R.id.rv_card);
    Add = findViewById(R.id.btn_basket_pay);
    price_total = findViewById(R.id.totalPrice);
    mydb=new dbhandler(getApplicationContext());
    back_btn=findViewById(R.id.back);
    total=findViewById(R.id.total);

   mydb.open();

    facultyAdapter = new FacultyAdapter(getApplicationContext(), mydb.display());
    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), 
   LinearLayoutManager.VERTICAL, false));
    recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(facultyAdapter);  

   facultyAdapter.registerAdapterDataObserver(observer);
    posts= mydb.display();

    for (int i= 0; i < posts.size(); i++){
       facultyAdapter.calculateTotalF(i);      
        name=""+posts.get(i).getName();
    }

    items = new Faculty(id,title, status, price, sum);
    SharedPreferences preferences = getSharedPreferences("prefs",MODE_PRIVATE);
    facultyAdapter.notifyDataSetChanged();
    items.setSum(String.valueOf(price_total.getText()));

    //////////////////////////////////
    mydb.close();

    total.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          //  price_total.setText(""+ bundle.getString(qty_dkey));
        }
    });
       ////////////////////////////////////////////////
    back_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(cart.this, MainActivity.class));
            finish();
        }
    });
      //////////////////////////
    ItemTouchHelper.SimpleCallback simpleCallback=new RecyclerItemTouchHelper(0,ItemTouchHelper.LEFT 
   |ItemTouchHelper.RIGHT,this);
    new ItemTouchHelper(simpleCallback).attachToRecyclerView(recyclerView);
    //////////////////////////////////////////////////
    Add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           add();
        }
    });
  }
  //////////////////////////////////////////////////////////////////////////
 public int calculateMealTotal(){
 int mealTotal = 0;
for(Faculty order : posts){
    mealTotal +=Integer.parseInt(order.getPrice()) * order.getQty();
    Log.d("qtyad",""+order.getQty());
    Log.d(" mealTotal",""+ mealTotal);
}

return mealTotal;
}

RecyclerView.AdapterDataObserver observer = new RecyclerView.AdapterDataObserver() {
    @Override
    public void onChanged() {
        super.onChanged();
        setMealTotal();
        Log.d("ob","ob");

    }
};
public void setMealTotal(){
    price_total.setText(" "+ calculateMealTotal());
}

display in database在数据库中显示

    public List<Faculty> display(){

    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT  * FROM " + TBL_NAME ;
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor!= null)
        cursor.moveToFirst();
    List<Faculty> facultyList = new ArrayList<>();
    try {
        do{

            Faculty faculty = new Faculty(id,title, status, price, image);
            faculty.setId(cursor.getString(0));
            faculty.setName(cursor.getString(1));
            faculty.setPrice(cursor.getString(3));
            faculty.setQty(cursor.getInt(4));
            faculty.setImage(cursor.getString(2));
            // faculty.setQty(cursor.getString(3));
            facultyList.add(faculty);
        }while (cursor.moveToNext());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return facultyList;
}

Your issue is the reference of the object.你的issue参考object。

You are passing one object in Adapter and using another on Activity.您正在 Adapter 中传递一个 object 并在 Activity 中使用另一个。

facultyAdapter = new FacultyAdapter(getApplicationContext(), mydb.display()); //one object

and saving in post using same db function并使用相同的数据库 function 保存在帖子中

 posts= mydb.display(); //creates another object

What you can do is shift posts= mydb.display();你可以做的是 shift posts= mydb.display(); above adapter assignment.以上适配器分配。

So your code look like所以你的代码看起来像

posts= mydb.display();
facultyAdapter = new FacultyAdapter(getApplicationContext(), posts);

Now on Add button onClickListener use your setMealTotal() after add() .现在在添加按钮 onClickListener 上使用您的setMealTotal()add()

Add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           add();
           setMealTotal()
        }
});

EDIT编辑

For updating your total price you need change the values of your quantity on FacultyList and also on the DB where you are saving the cart data.要更新总价,您需要更改 FacultyList 以及保存购物车数据的数据库中的数量值。 Currently you are updating the UI manually on adapter BindViewHolder which is not recommended as its the job of an adapter to update the UI according to the data with which it is binded.当前,您正在适配器 BindViewHolder 上手动更新 UI,不建议这样做,因为适配器的工作是根据绑定的数据更新 UI。 Check Android Room or CursorAdpter with Recyclerview to easily perform these task.使用 Recyclerview 检查 Android Room 或 CursorAdpter 以轻松执行这些任务。

Currently what you can do is create an interface to notify your activity about the changes in your cart.目前您可以做的是创建一个界面来通知您的活动有关购物车中的更改。

interface ICartModification{
  void increment(int qty, Faculty faculty)
  void decrement(int qty, Faculty faculty)
} 

Implement this interface on CartActivity在 CartActivity 上实现这个接口

@Overrides
void increment(int qty, Faculty faculty){
   faculty.setQty(qty)

    //update DB here
   facultyAdapter.notifyDataSetChanged()
   setMealTotal()
}
@Overrides
void decrement(int qty, Faculty faculty){
   if(qty<=0)
      posts.remove(faculty)
   else
      faculty.setQty(qty)

   //update DB here
   facultyAdapter.notifyDataSetChanged()
   setMealTotal()
}

and pass reference of Activity to adapter.并将 Activity 的引用传递给适配器。

facultyAdapter = new FacultyAdapter(this, mydb.display());

Now on your Inc and Dcr call this update function as follows现在在您的 Inc 和 Dcr 上调用此更新 function,如下所示

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

           if(context instanceof ICartModification){
               ((ICartModification)context).increment(faculty.getQty()+1, faculty);
           }
       }
   });

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

               if(context instanceof ICartModification){
                   ((ICartModification)context).decrement(faculty.getQty()-1, faculty);
               }
           }
       });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM