在recyclerview中计算物品的总价

时间:2018-08-05 08:09:03

标签: java android android-recyclerview subtotal

我使用排球库并从服务器加载json并将其显​​示在recyclerview中。我想创建一个购物车并计算recyclerview项目的总价。我的问题是这些物品的总费用无法计算。
请帮助我

这是我的代码:

public class checkout extends AppCompatActivity {
    String shop = SHOP;
    List<Product6> productList6;
    ProductsAdapter6 productsAdapter6;

    RecyclerView recyclerView;

    private ProductsAdapter6 adapter6;

    private GridLayoutManager layoutManager;

    RecyclerView.LayoutManager RecyclerViewLayoutManager;
    private TextView subTotal;
    private double mSubTotal = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkout);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        RecyclerViewLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(RecyclerViewLayoutManager);
        adschild2();

        productList6 = new ArrayList<>();

        subTotal = (TextView) findViewById(R.id.sub_total);

        mSubTotal = grandTotal(productList6);
        subTotal.setText(String.valueOf(mSubTotal));

    }

    private int grandTotal(List<Product6> items) {

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

        return totalPrice;
    }

    private void adschild2() {

        StringRequest stringRequest = new StringRequest(Request.Method.GET, shop, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                try {
                    // converting the string to json array object
                    JSONArray array = new JSONArray(response);

                    // traversing through all the object
                    for (int i = 0; i < array.length(); i++) {

                        // getting product object from json array
                        JSONObject product6 = array.getJSONObject(i);

                        // adding the product to product list
                        productList6.add(new Product6(product6.getInt("id"), product6.getDouble("back")));

                    }
                    // creating adapter object and setting it to recyclerview
                    ProductsAdapter6 adapter6 = new ProductsAdapter6(checkout.this, productList6);
                    recyclerView.setAdapter(adapter6);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        // adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }
}

2 个答案:

答案 0 :(得分:1)

请将其添加到适配器类中,然后从活动中调用adapter.getGrandTotal()

public List<Product6> mItems = new ArrayList()

public void setData(List<Product6> items) {
    this.mItems = items;
    notifyDataSetChanged()
}

private int grandTotal() {
    int totalPrice = 0;
    for (int i = 0; i < mItems.size(); i++) {
        totalPrice += mItems.get(i).getBack();
    }
    return totalPrice;
}

/* onCreateViewHolder and onBindViewHolder remains same */

根据评论,请找到修改后的类

package com.example.pix.shoping;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

    private List<Movie> moviesList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, year, genre;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            genre = (TextView) view.findViewById(R.id.genre);
            year = (TextView) view.findViewById(R.id.year);
        }
    }


    public MoviesAdapter(List<Movie> moviesList) {
        this.moviesList = moviesList;
    }

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

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Movie movie = moviesList.get(position);
        holder.title.setText(movie.getTitle());
        holder.genre.setText(movie.getGenre());
        holder.year.setText(movie.getYear() + "");
    }

    public void setData(List<Movie> items) {
        this.moviesList = items;
        notifyDataSetChanged();
    }

    public int grandTotal() {
        int totalPrice = 0;
        for (int i = 0; i < moviesList.size(); i++) {
            totalPrice += moviesList.get(i).getYear();
        }
        return totalPrice;
    }

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

MainActivity

package com.example.pix.shoping;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Movie> movieList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MoviesAdapter mAdapter;
    private TextView subTotal;
    private double mSubTotal = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new MoviesAdapter(movieList);

        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);

        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.setAdapter(mAdapter);

        prepareMovieData();


        subTotal = (TextView) findViewById(R.id.sub_total);

        // This whould be called on a user action mostly like a button click
        mSubTotal = mAdapter.grandTotal();
        subTotal.setText("توم" + String.valueOf(mSubTotal) + " قیمت کل");
    }

    /**
     * Prepares sample data to provide data set to adapter
     */
    private void prepareMovieData() {
        Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", 2015);
        movieList.add(movie);

        movie = new Movie("Inside Out", "Animation, Kids & Family", 2015);
        movieList.add(movie);

        movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", 2015);
        movieList.add(movie);

        movie = new Movie("Shaun the Sheep", "Animation", 2015);
        movieList.add(movie);

        // notify adapter about data set changes
        // so that it will render the list with new data
        mAdapter.notifyDataSetChanged();
    }

}

screenshot

答案 1 :(得分:0)

您的呼叫

mSubTotal = grandTotal(productList6);

应该在您的通话请求

之内
adschild2()

在onResponse中-解析JSON之后。

原因是adschild2是一个异步函数,仅在调用onResponse之后才填充productList6,而对grandTotal的调用是同步的并计算空列表的总和。