gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:30:15 25 4
gpt4 key购买 nike

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

我的问题

更改商品编号后,如何更改商品价格?(某个编号是按每个商品计算总价,但更改编号后,总价不变。)

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

最佳答案

您的问题是对象的引用。

您在 Adapter 中传递一个对象,并在 Activity 上使用另一个对象。

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

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

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

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

所以你的代码看起来像

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

现在,在 ClickListener 上的“添加”按钮上,在 add() 之后使用您的 setMealTotal()

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

编辑

要更新总价,您需要更改FacultyList 以及保存购物车数据的数据库上的数量值。目前,您正在适配器 BindViewHolder 上手动更新 UI,不建议这样做,因为适配器的工作是根据其绑定(bind)的数据更新 UI。使用 Recyclerview 检查 Android Room 或 CursorAdpter 以轻松执行这些任务。

目前您可以做的是创建一个界面来通知您的 Activity 有关购物车中的更改。

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

在CartActivity上实现该接口(interface)

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

并将 Activity 的引用传递给适配器。

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

现在在您的 Inc 和 Dcr 上调用此更新函数,如下所示

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

关于java - 如何计算购物车中的总价?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com