-2

Je veux calculer le prix des articles dans une liste et stocker la valeur dans sharedpreference. Chaque article a un prix qui prend la forme d'un double. Le problème est lorsque j'utilise ma méthode, il ne prend en compte qu'un élément de la liste et calcule pour cette valeur. J'utilise un NumberPicker pour changer la quantité des articles.Calcul du prix total des articles dans une liste d'articles dans un recyclerview

Voici mon adaptateur pour gérer la liste des éléments qui seront affichés sur le RecyclerView:

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> { 
    private List<SingleItem> items; 
    private SessionManager sessionManager; 
    private Context context; 
    private int pos; 

    public CartAdapter() { 
    } 

    public CartAdapter(Context context, List<SingleItem> items) { 
     this.items = items; 
     this.context = context; 
     sessionManager = new SessionManager(context); 

    } 

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

    @Override 
    public void onBindViewHolder(final ViewHolder holder, final int position) { 
     final SingleItem singleItem = items.get(position); 
     holder.tv_title.setText(singleItem.getTitle()); 
     holder.tv_price.setText("Ksh: " + singleItem.getPrice()); 
     Picasso.with(context).load(singleItem.getUrl()).fit().into(holder.imgcart); 
     holder.numcart.setMinValue(1); 
     holder.numcart.setMaxValue(15); 
     holder.numcart.setWrapSelectorWheel(false); 
     int qty = holder.numcart.getValue(); 
     getTotal(qty, singleItem.getPrice()); 
    } 

    public double getTotal(int value, double amount){ 

     double totalamount; 
     double amountall = amount; 
     int quantity = value; 
     totalamount = amountall * quantity; 
     sessionManager.grandtotal("Ksh: " + totalamount); 
     return totalamount; 
    } 


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

    public void removeItem(SingleItem item) { 
     sessionManager.removeitem(context,item); 
     items.remove(item); 
     notifyDataSetChanged(); 
    } 

    public class ViewHolder extends RecyclerView.ViewHolder { 
     TextView tv_price; 
     TextView tv_title; 
     NumberPicker numcart; 
     ImageView imgcart; 

     public ViewHolder(View view) { 
      super(view); 

      tv_price = (TextView) view.findViewById(R.id.titlecart); 
      tv_title = (TextView) view.findViewById(R.id.pricecart); 
      numcart = (NumberPicker) view.findViewById(R.id.pickercart); 
      imgcart = (ImageView) view.findViewById(R.id.imgcart); 
     } 
    } 
} 

Voici comment j'afficher le RecyclerView sur le fragment:

public class Details extends Fragment { 
    private RecyclerView RecyclerDetails; 
    private TextView CartPrice; 
    private CheckBox CheckCart; 
    private List<SingleItem> list; 
    private CartAdapter adapter; 
    private boolean add = false; 
    private Paint p = new Paint(); 
    private SessionManager sessionManager; 
    private int pos; 



    public Details() { 
     // Required empty public constructor 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_details, container, false); 

     RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart); 
     CartPrice = (TextView) view.findViewById(R.id.tvcarttotal); 
     CheckCart = (CheckBox) view.findViewById(R.id.chkcart); 

     sessionManager = new SessionManager(getContext()); 

     Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_SHORT,true).show(); 

     RecyclerDetails.setHasFixedSize(true); 
     RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext()); 
     RecyclerDetails.setLayoutManager(layoutManager); 

     list = sessionManager.getItems(getContext()); 

     HashMap<String,String> map = sessionManager.itemstostring(); 
     String data = map.get(SessionManager.KEY_ITEMS); 
     Log.i(Constants.TAG,data); 

     HashMap<String,String> tot = sessionManager.getgrandtotal(); 
     String total = tot.get(SessionManager.KEY_TOTAL); 

     CartPrice.setText(total); 

     CheckCart.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (((CheckBox) v).isChecked()){ 
        sessionManager.saveditems("true"); 
       } else { 
        sessionManager.saveditems("false"); 
       } 
      } 
     }); 

     RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

      } 
     })); 


     if(list != null){ 
      adapter = new CartAdapter(getContext(),list); 
      RecyclerDetails.setAdapter(adapter); 
      } 

     initswipe(); 
     return view; 
    } 

    private void initswipe() { 
     ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { 

      @Override 
      public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { 
       return false; 
      } 

      @Override 
      public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { 
       int position = viewHolder.getAdapterPosition(); 

       if (direction == ItemTouchHelper.RIGHT) { 
        adapter.removeItem(list.get(position)); 
        sessionManager.saveitems(getContext(),list); 

       } 

      } 

      @Override 
      public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { 

       Bitmap icon; 
       if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){ 

        View itemView = viewHolder.itemView; 
        float height = (float) itemView.getBottom() - (float) itemView.getTop(); 
        float width = height/3; 

        if(dX > 0){ 
         p.setColor(Color.parseColor("#14a895")); 
         RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX,(float) itemView.getBottom()); 
         c.drawRect(background,p); 
         icon = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_delete); 
         RectF icon_dest = new RectF((float) itemView.getLeft() + width ,(float) itemView.getTop() + width,(float) itemView.getLeft()+ 2*width,(float)itemView.getBottom() - width); 
         c.drawBitmap(icon,null,icon_dest,p); 
        } else { 
         p.setColor(Color.parseColor("#14a895")); 
         RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom()); 
         c.drawRect(background,p); 
         icon = BitmapFactory.decodeResource(getResources(),android.R.drawable.ic_menu_delete); 
         RectF icon_dest = new RectF((float) itemView.getRight() - 2*width ,(float) itemView.getTop() + width,(float) itemView.getRight() - width,(float)itemView.getBottom() - width); 
         c.drawBitmap(icon,null,icon_dest,p); 
        } 
       } 
       super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); 
      } 
     }; 
     ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); 
     itemTouchHelper.attachToRecyclerView(RecyclerDetails); 
    } 

} 

Et enfin, voici la fonction que j'utilise pour stocker la valeur du total de tous les éléments de la liste

public void grandtotal (String total){ 
     editor.putString(KEY_TOTAL,total); 
     editor.commit(); 
    } 

    public HashMap<String, String> getgrandtotal(){ 
     HashMap<String, String> tot = new HashMap<>(); 
     tot.put(KEY_TOTAL,pref.getString(KEY_TOTAL,null)); 
     return tot; 
    } 

Y at-il une fonction que je n'ai pas incluse dans le fragment où j'affiche le RecyclerView avec les éléments?

Est-ce juste un petit changement nécessaire?

+0

vous calculez uniquement le prix d'un article, c'est pourquoi cela ne vous donne que le prix total. Mettre une boucle for et calculer le prix total à l'intérieur de la boucle en ajoutant le prix actuel au total précédent –

Répondre

2
private int grandTotal(List<SingleItem> items){ 

int totalPrice = 0; 
for(int i = 0 ; i < items.size(); i++) { 
    totalPrice += items.get(i).getPrice(); 
} 

return totalPrice; 
} 

c'est la méthode u besoin de mettre en œuvre pour obtenir le grand prix total. Vous pouvez appeler cette méthode lorsque vous ajoutez un élément ou supprimez un élément de la liste.

+0

Thats grand monsieur, mais où puis-je mettre cette fonction? –

+0

vous pouvez le mettre où vous voulez obtenir le prix total. Vous pouvez continuer à mettre à jour la valeur totale chaque fois que vous supprimez les éléments de la liste comme la méthode removeItem (SingleItem item) dans l'adaptateur. – nitish29