如何添加列表视图的所有价格并将其显示在底部的文本视图中?

时间:2018-10-25 09:40:00

标签: android firebase

我正在开发购物应用程序。我有一个包含价格和数量的列表视图。所有单元格的价格和数量的乘积应显示在底部的文本视图中。如何做到这一点?

先谢谢了。

适配器类

公共类CustomAdaptercartlist扩展了BaseAdapter {

private List<Model> filteredData = null;
private LayoutInflater mInflater;
private Activity i;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
Float p;
Float totalprice;


public CustomAdaptercartlist(Context context, List<Model> data, Activity i) {
    this.filteredData = data ;
    mInflater = LayoutInflater.from(context);
    this.i=i;
}



@Override
public int getCount() {
    int i;
    if(filteredData == null) {
        i = 0;
    }
    else {
        i = filteredData.size();
    }

    return i;
}

@Override
public Object getItem(int i) {
    return filteredData.get(i);
}

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

class ViewHolder {
    TextView name;
    TextView price;
    TextView quantity;
    TextView image_path,pq;
    ImageView image;
    LinearLayout layout;
    Button delete;
}
ViewHolder holder;

@SuppressLint({"ViewHolder", "InflateParams", "SetTextI18n", "NewApi"})
@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    holder= new ViewHolder();

    //===================initializing identitifiers===============//

    convertView = mInflater.inflate(R.layout.row_search_iteam_cartlist, null);
    holder.name =  convertView.findViewById(R.id.name);
    holder.price =  convertView.findViewById(R.id.price);
    holder.quantity =  convertView.findViewById(R.id.quantity);
    holder.image_path =  convertView.findViewById(R.id.ip);
    holder.image =  convertView.findViewById(R.id.image);
    holder.image_path.setClipToOutline(true);
    holder.delete =  convertView.findViewById(R.id.delete);
    holder.pq =  convertView.findViewById(R.id.pq);
    convertView.setTag(holder);

    //======================== setting values for listview cell====================//
    holder.name.setText(filteredData.get(position).getName());
    holder.price.setText("$"+ filteredData.get(position).getPrice());
    int qty = Integer.parseInt(filteredData.get(position).getqty());
    Float pri = Float.valueOf(filteredData.get(position).getPrice());
    holder.image_path.setText(filteredData.get(position).getImage_path());
    holder.quantity.setText(filteredData.get(position).getqty());
    totalprice = qty * pri;
    holder.pq.setText(qty + "*" + pri + "=" + totalprice);

    final String user_id;
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    user_id = mAuth.getUid();


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


            db.collection("UserProfile").document(user_id).collection("Cart")
                    .document(filteredData.get(position).getProductId()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    DocumentSnapshot documentSnapshot = task.getResult();
                    if(documentSnapshot.exists()){

                        final int q = Integer.parseInt(documentSnapshot.getString("Quantity"));
                        String sid = documentSnapshot.getString("StoreId");
                        String pid = documentSnapshot.getString("ProductId");
                        db.collection("Products").document(pid).collection("Stores").document(sid).
                                get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                DocumentSnapshot documentSnapshot = task.getResult();
                                if(documentSnapshot.exists()){

                                    Object sp = documentSnapshot.get("StorePrice");
                                    if(sp != null){
                                         p = Float.parseFloat(String.valueOf(sp));
                                    }

                                    Float totalprice1 = (q * p);
                                     totalprice = totalprice1 - totalprice;

                                }
                            }
                        });
                    }
                }
            });

            db.collection("UserProfile").document(user_id).collection("Cart")
                    .document(filteredData.get(position).getProductId()).delete()
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            Toast.makeText(i,"item deleted", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(i,Listviewcart.class);
                            i.startActivity(intent);

                        }
                    });
        }
    });

    // downloading image //

    if(filteredData.get(position).getImage_path() != null  && !TextUtils.isEmpty(filteredData.get(position).getImage_path())){

        Picasso.with(getApplicationContext()) //Context
                .load(filteredData.get(position).getImage_path()) //URL/FILE
                .fit()
                .into(holder.image);//an ImageView Object to show the loaded image;
    }
    return convertView;

}

}

java类

public class Listviewcart extends AppCompatActivity {

    FirebaseAuth mAuth;
    String user_id = "",price;
    ListView listView;
    List<Model> ls_data;
    CustomAdaptercartlist adapter;
    ProgressDialog pd;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    TextView shopperpay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listviewcart);
        setTitle("Wish List");



        if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        mAuth = FirebaseAuth.getInstance();
        user_id = mAuth.getUid();
        listView = findViewById(R.id.list);
        shopperpay = findViewById(R.id.shopperpay);
        ls_data=new ArrayList<>();



        //============progress diologue=========//
        pd = new ProgressDialog(this);
        pd.setTitle("Please Wait...");
        pd.setCancelable(false);
        pd.show();

        wishlistdata();


    }


    private void wishlistdata() {

        db.collection("UserProfile").document(user_id).collection("Cart")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {

                        if (task.isSuccessful() && !task.getResult().isEmpty()) {

                            for (final DocumentSnapshot document : task.getResult()) {

                                final String name = document.getString("ProductId");
                                String sid = document.getString("StoreId");
                                final String qty = document.getString("Quantity");
                                db.collection("Stores").document(sid).collection("Inventory").document(name).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                        DocumentSnapshot document = task.getResult();
                                        if (document.exists()) {
                                            String ProductName = task.getResult().getString("ProductName");
                                            Object ProductPrice = task.getResult().get("StorePrice");
                                            if (ProductPrice != null) {

                                                price = String.valueOf(ProductPrice);
                                            }
                                            String ProductImage = task.getResult().getString("Image");
                                            if (ProductName != null && ProductPrice != null && ProductImage != null) {
                                                Model m = new Model();
                                                m.setName(ProductName);
                                                m.setPrice(price);
                                                m.setImage_path(ProductImage);
                                                m.setProductId(name);
                                                m.setqty(qty);
                                                ls_data.add(m);
                                            }
                                            try {
                                                adapter = new CustomAdaptercartlist(Listviewcart.this, ls_data, Listviewcart.this);
                                            } catch (Exception ex) {
                                                Log.e("Error", "Dashboard : " + ex);
                                            }

                                            listView.setAdapter(adapter);
                                            pd.dismiss();
                                        } else {
                                            Log.e("firestore", "Error getting documents.", task.getException());
                                        }
                                    }
                                });
                            }

                        }
                    }
                });


    }

row_serach_iteam_cartlist

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="#EFE9EF">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginTop="8dp"
        android:orientation="horizontal"
        android:padding="@dimen/activity_horizontal_margin"
        app:cardCornerRadius="4dp"
        android:elevation="2dp"
        tools:targetApi="n">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_margin="10dp">

            <ImageView
                android:id="@+id/image"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:src="@drawable/ic_action_placeholder"
                android:scaleType="fitXY"
                android:layout_marginEnd="8dp"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">



                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/name"
                    android:textSize="14sp"
                    android:layout_marginStart="6dp"
                    android:layout_marginEnd="40dp"
                    android:textColor="#58595d"
                    android:id="@+id/name"
                    android:fontFamily="@font/poppinsmedium"
                    tools:targetApi="n"/>
                <Button
                    android:id="@+id/delete"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="@drawable/ic_action_delete"
                    android:textSize="14sp"
                    android:layout_alignParentEnd="true"
                    android:layout_marginStart="6dp"
                    android:layout_marginEnd="10dp"
                    android:textColor="#58595d"
                    android:fontFamily="@font/poppinsmedium"
                    tools:targetApi="n"/>

                </RelativeLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:layout_marginStart="6dp"
                    >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/poppinsmedium"                                    android:gravity="start"
                        android:text="Quantity :"
                        android:textAlignment="textStart"
                        android:textColor="#58595d"
                        android:textSize="14sp"
                        tools:targetApi="n" />

                    <TextView
                        android:id="@+id/quantity"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="4dp"
                        android:fontFamily="@font/poppinsregular"
                        android:gravity="start"
                        android:text="qty"
                        android:textAlignment="textStart"
                        android:textColor="#000000"
                        android:textSize="14sp"
                        tools:targetApi="n" />
                </LinearLayout>
                <TextView
                    android:id="@+id/price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/poppinsmedium"
                    android:gravity="start"
                    android:text="qty"
                    android:textAlignment="textStart"
                    android:textColor="#000000"
                    android:textSize="14sp"
                    android:layout_marginStart="8dp"
                    tools:targetApi="n" />

                <TextView
                    android:id="@+id/pq"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/poppinsmedium"
                    android:gravity="start"
                    android:text="total"
                    android:textAlignment="textStart"
                    android:textColor="#000000"
                    android:textSize="14sp"
                    android:layout_marginStart="8dp"
                    tools:targetApi="n" />
                <TextView
                    android:id="@+id/ip"
                    android:visibility="gone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fontFamily="@font/poppinsmedium"
                    android:gravity="start"
                    android:textAlignment="textStart"
                    android:textColor="#000000"
                    android:textSize="14sp"
                    android:layout_marginStart="8dp"
                    tools:targetApi="n" />

            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>


</LinearLayout>

2 个答案:

答案 0 :(得分:1)

我将举例说明。如果我对您的问题的理解有误,请纠正我。

  

假设您有一个名为 ItemsModel

的ModelClass

ItemsModel.java

public class ItemsModel {
String itemName, itemUrl;
int price;

public ItemsModel(String itemName, String itemUrl, int price) {
    this.itemName = itemName;
    this.itemUrl = itemUrl;
    this.price = price;
}

public String getItemName() {
    return itemName;
}

public String getItemUrl() {
    return itemUrl;
}

public int getPrice() {
    return price;
}}
  

将所有已添加购物车的商品放入另一个模型类

CartModel.java

public class CartModel {
String itemName, itemUrl;
int price, quantity;

public CartModel(String itemName, String itemUrl, int price, int quantity) {
    this.itemName = itemName;
    this.itemUrl = itemUrl;
    this.price = price;
    this.quantity = quantity;
}

public String getItemName() {
    return itemName;
}

public String getItemUrl() {
    return itemUrl;
}

public int getPrice() {
    return price;
}

public int getQuantity() {
    return quantity;
}}
  

因为您将在ArrayList<CartModel> cartList中传递购物车项目。

 int total = 0;
for(int i = 0; i < cartList.size(); i++){
      int quantity = cartList.get(i).getQuantity();
      int pricePerUnit = cartList.get(i).getPrice();

      total = total + (pricePerUnit * quantity);
}
  

可变总计是所有农产品的总计。

希望这会有所帮助

答案 1 :(得分:0)

这是解决方案。在获取数据的同时在for循环中执行计算

private void wishlistdata() {

        db.collection("UserProfile").document(user_id).collection("Cart")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {

                        if (task.isSuccessful() && !task.getResult().isEmpty()) {

                            for (final DocumentSnapshot document : task.getResult()) {

                                final String name = document.getString("ProductId");
                                String sid = document.getString("StoreId");
                                final String qty = document.getString("Quantity");
                                db.collection("Stores").document(sid).collection("Inventory").document(name).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                        DocumentSnapshot document = task.getResult();
                                        if (document.exists()) {
                                            String ProductName = task.getResult().getString("ProductName");
                                            Object ProductPrice = task.getResult().get("StorePrice");
                                            if (ProductPrice != null) {

                                                price1 = String.valueOf(ProductPrice);
                                                p = Float.valueOf(String.valueOf(ProductPrice));
                                            }
                                            String ProductImage = task.getResult().getString("Image");
                                            if (ProductName != null && ProductPrice != null && ProductImage != null) {

                                                Float a = p * Integer.parseInt(qty);
                                                total = total + a;
                                                shopperpay.setText(String.valueOf(total));
                                                pd.dismiss();
                                            }

                                        } else {
                                            pd.dismiss();
                                            Log.e("firestore", "Error getting documents.", task.getException());
                                        }
                                    }
                                });

                            }

                        }
                    }
                });


    }