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

问题描述 投票:0回答:1

当用户按下添加按钮时,我的应用程序的购物车部分会离线实现。产品存储在数据库中,然后显示在购物车中。

我的问题

更改产品编号选择器后如何更改产品价格?(一个数字的总价是从每个产品中计算出来的,但是更改数量之后,总价不变。)

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

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

在数据库中显示

    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;
}
android android-studio shopping-cart
1个回答
0
投票

您的问题是对象的引用。

您正在适配器中传递一个对象,并在Activity上使用另一个对象。

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

并使用相同的db函数保存在帖子中

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

您可以做的是将posts= mydb.display();移到适配器分配上方。

所以您的代码看起来像

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

现在单击[添加到新按钮] onClickListener在setMealTotal()之后使用您的add()

Add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           add();
           setMealTotal()
        }
});
© www.soinside.com 2019 - 2024. All rights reserved.