How to get total by adding all the recycler views rows - java

I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS

why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}

Related

The Data From My Recyclerview Is not Updated

Hello everyone i have a problem when inserting data. I have a bunch of code like below:
// This is My ExpenceActiviy
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityExpenseBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.fabExpense.setOnClickListener(v -> {
Intent newExpense = new Intent(this, AddExpenseActivity.class);
startActivity(newExpense);
});
expenseDatabase = ExpenseDatabase.getInstance(this);
expenseDao = expenseDatabase.getDao();
expenseAdapter = new ExpenseAdapter(this);
binding.rvExpense.setAdapter(expenseAdapter);
binding.rvExpense.setLayoutManager(new LinearLayoutManager(this));
List<ExpenseTable> expenseTables = expenseDao.getAll();
for (int i=0; i <expenseTables.size(); i++) {
if (expenseTables.get(i).isIncome()) {
income = income+expenseTables.get(i).getAmount();
} else {
expense = expense+expenseTables.get(i).getAmount();
}
expenseAdapter.add(expenseTables.get(i));
}
binding.tvExpense.setText(String.valueOf(expense));
binding.tvIncome.setText(String.valueOf(income));
long balance = income-expense;
binding.tvBalance.setText(String.valueOf(balance));
}
Here is my ExpenseAdapter
public class ExpenseAdapter extends RecyclerView.Adapter<ExpenseAdapter.ExpenseViewHolder> {
private final Context mContext;
private final List<ExpenseTable> expenseTableList;
public ExpenseAdapter(Context mContext) {
this.mContext = mContext;
expenseTableList = new ArrayList<>();
}
public void add(ExpenseTable expenseTable) {
expenseTableList.add(expenseTable);
notifyDataSetChanged();
}
#NonNull
#Override
public ExpenseAdapter.ExpenseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_expense_list, parent, false);
return new ExpenseViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ExpenseAdapter.ExpenseViewHolder holder, int position) {
ExpenseTable expenseTable = expenseTableList.get(position);
holder.title.setText(expenseTable.getPaymentType());
holder.amount.setText(String.valueOf(expenseTable.getAmount()));
holder.description.setText(expenseTable.getDescription());
if (expenseTable.isIncome()) {
holder.status.setText(mContext.getString(R.string.income));
} else {
holder.status.setText(mContext.getString(R.string.expense));
}
}
#Override
public int getItemCount() {
return expenseTableList.size();
}
public static class ExpenseViewHolder extends RecyclerView.ViewHolder{
TextView amount, status, title, description;
public ExpenseViewHolder(#NonNull View itemView) {
super(itemView);
status = itemView.findViewById(R.id.tv_isIncome);
amount = itemView.findViewById(R.id.tv_amount);
title = itemView.findViewById(R.id.tv_title);
description = itemView.findViewById(R.id.tv_description);
}
}
}
If i put those code in onResume just like below:
#Override
protected void onResume() {
super.onResume();
expenseDatabase = ExpenseDatabase.getInstance(this);
expenseDao = expenseDatabase.getDao();
expenseAdapter = new ExpenseAdapter(this);
binding.rvExpense.setAdapter(expenseAdapter);
binding.rvExpense.setLayoutManager(new LinearLayoutManager(this));
List<ExpenseTable> expenseTables = expenseDao.getAll();
for (int i=0; i <expenseTables.size(); i++) {
if (expenseTables.get(i).isIncome()) {
income = income+expenseTables.get(i).getAmount();
} else {
expense = expense+expenseTables.get(i).getAmount();
}
expenseAdapter.add(expenseTables.get(i));
}
binding.tvExpense.setText(String.valueOf(expense));
binding.tvIncome.setText(String.valueOf(income));
long balance = income-expense;
binding.tvBalance.setText(String.valueOf(balance));
}
The list updated but everytime i push or refresh the page, the balance, income and expense increasing by itself. that make me annoying although its not effect to recyclerview list. I am sorry if my english worst, this is not my native language.
can anybody help me, would be appreciated, thank you in advanced

Fetching image using Picasso

Here in the given below code, I am trying to display in the image in recyclerview in the imageview after fetching it using picasso, it won't show error or app won't crash either but image won't be displayed, it either shows:
"I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread."
Or
W/RecyclerView: No adapter attached; skipping layout
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
LayoutInflater inflater;
List<Lists> lst;
private ItemClickListsner mItemListener;
public Adapter(Context ctx, List<Lists> lst, ItemClickListsner itemClickListsner) {
this.inflater = LayoutInflater.from(ctx);
this.lst = lst;
this.mItemListener = itemClickListsner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// final Lists temp = lst.get(position);
holder.id.setText(lst.get(position).getId());
holder.name.setText(lst.get(position).getName());
holder.prc.setText(lst.get(position).getPrc());
holder.add.setText(lst.get(position).getAddress());
holder.description.setText(lst.get(position).getDes());
holder.park.setText(lst.get(position).getGarage());
holder.net.setText(lst.get(position).getNet());
holder.email.setText(lst.get(position).getMail());
holder.number.setText(lst.get(position).getPnumber());
holder.post.setText(lst.get(position).getTle());
holder.date.setText(lst.get(position).getCrt());
Picasso.with(inflater.getContext())
.load(lst.get(position).getMimage())
.placeholder(R.drawable.bed)
.fit()
.into(holder.ImgView);
holder.itemView.setOnClickListener(view -> {
mItemListener.onItemClick(lst.get(position));
});
}
#Override
public int getItemCount() {
return lst.size();
}
public interface ItemClickListsner{
void onItemClick(Lists lst);
}
public void filterList(ArrayList<Lists> filteredList) {
lst = filteredList;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView id, name, add, prc, description, park, net, post,email,number,date;
ImageView ImgView;
// CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.textViewRecy1);
name = itemView.findViewById(R.id.textViewRecy2);
prc = itemView.findViewById(R.id.textViewRecy3);
add = itemView.findViewById((R.id.textViewRecy4));
description = itemView.findViewById(R.id.textViewRecy5);
park = itemView.findViewById(R.id.textViewRecy6);
net = itemView.findViewById(R.id.textViewRecy7);
post = itemView.findViewById(R.id.textViewRecy8);
email = itemView.findViewById(R.id.textViewRecy9);
number = itemView.findViewById(R.id.textViewRecy10);
date = itemView.findViewById(R.id.textViewRecy11);
ImgView = itemView.findViewById(R.id.ImageRecy);
}
}
}
Activity Code
private void extractList() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
//Log.d("tags", "error: " + jsonObject);
Lists lists = new Lists();
lists.setName(jsonObject.getString("title").toString());
lists.setAddress(jsonObject.getString("location").toString());
lists.setPrc(jsonObject.getString("price").toString());
lists.setDes(jsonObject.getString("description").toString());
lists.setGarage(jsonObject.getString("parking").toString());
lists.setNet(jsonObject.getString("internet").toString());
lists.setMail(jsonObject.getString("email").toString());
lists.setPnumber(jsonObject.getString("phone_number").toString());
lists.setTle(jsonObject.getString("poster").toString());
lists.setCrt(jsonObject.getString("created").toString());
lists.setMimage(jsonObject.getString("photo1").toString());
String p = jsonObject.getString("photo1").toString();
Log.e("kk","msg"+p);
lst.add(lists);
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), lst, new Adapter.ItemClickListsner() {
#Override
public void onItemClick(Lists lst) {
// startActivity(new Intent(HomeActivity.this,roomsDesc.class));
Intent intent = new Intent(HomeActivity.this, roomsDesc.class);
intent.putExtra("title",lst.getName());
intent.putExtra("price",lst.getPrc());
intent.putExtra("location",lst.getAddress());
intent.putExtra("description",lst.getDes());
intent.putExtra("parking",lst.getGarage());
intent.putExtra("internet",lst.getNet());
intent.putExtra("email",lst.getMail());
intent.putExtra("phone_number",lst.getPnumber());
intent.putExtra("poster",lst.getTle());
intent.putExtra("created",lst.getCrt());
intent.putExtra("photo1",lst.getMimage());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
HomeActivity.this.startActivity(intent);
}
});
recyclerView.setAdapter(adapter);
}

I have problem with recycler view and fragments?

I write this code but not show me anything and in logcat have no error
and I have three classes for this code Adapter, recyclertouchlistener and fragments code...
my code in below
this code for fragment :
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalRecyclerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical_recycler,
container, false);
showProduct();
rcVertical = view.findViewById(R.id.rcVertical);
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getActivity(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
return view;
}
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loader.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}}
and i write this code for Adapter in a single class :
public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {
ArrayList<Products> ProductsList;
Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}}
RecyclerTouchListener :
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView,
final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}}
Please if you know whats the problem help me to debug it...
thank you
You need to notifyDataSetChanged() when you get the response.
Make the adapter as a class field
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
Adapter adapter; // <<< Change here
change the initialization (and every call of the adapter to the class field)
adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
And finally call notifyDataSetChanged() when you get the response
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
adapter.notifyDataSetChanged(); // <<< Change here
} catch (JSONException e) {
e.printStackTrace();
}
}
}...
...
}
UPDATE:
add attach the adapter to the RecyclerView when you receive the data
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
Adapter adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setAdapter(adapter); // <<< Change here

Updating TextView inside ListView Adapter from a Fragment

I have a price TextView in my OrderFragment which I would like to update onItemSelected of discount per item and discount per bill Spinner. I tried using notifyDataSetChanged on my ArrayList once I had change the price of my items but it did not update my ListView. The notifyDataSetChanged is working fine when I use it in different fragment for add and removing element from my ArrayList but updating price on the ArrayList for this doesn't seems to be working.
For update my discount per bill, I refer to various question but it doesn't seems to get it working : notifyDataSetChange not working from custom adapter, Android: notifyDataSetChanged(); not working, Android ListView not refreshing after notifyDataSetChanged and others also. Then I tried changing the TextView from my Fragment using ListView.getChildAt() but it is not working due to the ListView only loads the visible rows so, other rows that are not visible are not updated.
As for discount per item, I had it working but by using 2 Callback which seems to be not efficient.
OrderFragment
public class OrderFragment extends Fragment {
private ArrayList<Product> orderList = new ArrayList<Product>();
private ListView lvConfirmOrder;
private ListViewOrderAdapter lvConfirmOrderAdapter;
private TextView tvTotalOrderPrice;
private int totalOrderPrice;
private Spinner sBillDiscount;
private int billDiscount = 0;
private ItemClickListener itemClickListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_order, container, false);
activity = getActivity();
db = DatabaseHelper.getInstance(activity);
Bundle bundle = new Bundle();
orderList = getArguments().getParcelableArrayList("orderList");
tvTotalOrderPrice = (TextView) view.findViewById(R.id.tvShowTotalPrice);
sBillDiscount = (Spinner) view.findViewById(R.id.sBillDiscount);
lvConfirmOrder = (ListView) view.findViewById(R.id.lvConfirmOrder);
lvConfirmOrderAdapter = new ListViewOrderAdapter(activity, orderList, new ItemClickListener() {
#Override
public void onItemClick(Product product) {
}
#Override
public void onItemClick(ProductCategory productCategory) {
}
#Override
public void onItemClick(ArrayList<Product> productList) {
tvTotalOrderPrice.setText(String.format("%d",setTotalPrice()));
}
});
lvConfirmOrder.setAdapter(lvConfirmOrderAdapter);
// Get the total price of all items
totalOrderPrice = setTotalPrice();
// Set the total price into TextView
tvTotalOrderPrice.setText(String.format("%d",totalOrderPrice));
addItemsOnSBillDiscountAndPreselect(billDiscount);
sBillDiscount.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
float spinnerValue = Float.parseFloat(adapterView.getItemAtPosition(i).toString());
float discount = 1.0f - (spinnerValue/100.0f);
totalAfterDiscount(discount);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
return view;
}
private int setTotalPrice() {
int totalPrice = 0;
for (int index = 0; index < orderList.size(); index++) {
totalPrice += orderList.get(index).getOrderPrice();
}
return totalPrice;
}
// add items into spinner
public void addItemsOnSBillDiscountAndPreselect(int discount) {
List<Integer> list = new ArrayList<Integer>();
for(int index = 0; index <= 100; index++) {
list.add(index);
}
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(activity,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sBillDiscount.setAdapter(dataAdapter);
int spinnerPosition = dataAdapter.getPosition(discount);
sBillDiscount.setSelection(spinnerPosition);
}
public void totalAfterDiscount(float discount) {
float totalItemPrice[] = new float[orderList.size()];
for (int i = 0; i < orderList.size(); i++) {
totalItemPrice[i] = orderList.get(i).getOrderPrice() * discount;
}
TextView tvPrice;
for ( int i = 0 ; i < lvConfirmOrder.getCount() ; i++){
View v = getViewByPosition(i,lvConfirmOrder);
tvPrice = (TextView) v.findViewById(R.id.tvQtyPrice);
tvPrice.setText(String.valueOf(totalItemPrice[i]));
}
tvTotalOrderPrice.setText(String.format("%d",setTotalPrice()));
lvConfirmOrderAdapter.notifyDataSetChanged();
}
public View getViewByPosition(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition =firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition ) {
return listView.getAdapter().getView(position, listView.getChildAt(position), listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
ListViewOrderAdapter
public class ListViewOrderAdapter extends ArrayAdapter {
//to store the list of products
private ArrayList<Product> productList = new ArrayList<Product>();
private ItemClickListener itemClickListener;
private ViewHolder viewHolder;
private DiscountSpinnerListener discountSpinnerListener;
private static class ViewHolder {
TextView tvProductName;
TextView tvProductSku;
TextView tvPrice;
TextView tvProductNum;
TextView iAddQuantity;
TextView tvQuantity;
TextView tvQtyPrice;
TextView iMinusQuantity;
Spinner sDiscount;
TextView iDelete;
}
public ListViewOrderAdapter(Activity context, ArrayList<Product> listProduct, ItemClickListener itemClickListener){
super(context,R.layout.row_order , listProduct);
this.context = context;
this.productList = listProduct;
this.itemClickListener = itemClickListener;
}
public View getView(final int position, View view, ViewGroup parent) {
final Product product = productList.get(position);
if (view == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.row_order, null, false);
viewHolder.tvProductName = (TextView) view.findViewById(R.id.tvOrderProduct);
viewHolder.tvProductSku = (TextView) view.findViewById(R.id.tvOrderSKU);
viewHolder.tvPrice = (TextView) view.findViewById(R.id.tvProductPrice);
viewHolder.tvProductNum = (TextView) view.findViewById(R.id.tvOrderNum);
viewHolder.iAddQuantity = (TextView) view.findViewById(R.id.iAddQuantity);
viewHolder.tvQuantity = (TextView) view.findViewById(R.id.tvQuantity);
viewHolder.tvQtyPrice = (TextView) view.findViewById(R.id.tvQtyPrice);
viewHolder.iMinusQuantity = (TextView) view.findViewById(R.id.iMinusQuantity);
viewHolder.sDiscount = (Spinner) view.findViewById(R.id.sDiscount);
viewHolder.iDelete = (TextView) view.findViewById(R.id.iDelete);
// Cache the viewHolder object inside the fresh view
view.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) view.getTag();
}
//this code sets the values of the objects to values from the arrays
viewHolder.tvProductName.setText(product.getProduct_name());
viewHolder.tvProductSku.setText(product.getProduct_sku());
viewHolder.tvPrice.setText(String.valueOf(product.getPrice_max()));
String num = Integer.toString(position + 1);
viewHolder.tvProductNum.setText(num);
viewHolder.tvQuantity.setText(String.valueOf(product.getOrderQuantity()));
addItemsOnSDiscountAndPreselect(viewHolder,product.getDiscount_per_item());
viewHolder.sDiscount.setOnItemSelectedListener(new SpinnerListener(viewHolder, position, new DiscountSpinnerListener() {
#Override
public void onDiscountChange(TextView tvPrice, int pos, float price) {
if (position == pos) {
tvPrice.setText(String.valueOf(price));
itemClickListener.onItemClick(productList);
}
}
}));
font = Typeface.createFromAsset(context.getAssets(), "fonts/fontawesome-webfont.ttf" );
viewHolder.iAddQuantity.setTypeface(font);
viewHolder.iMinusQuantity.setTypeface(font);
viewHolder.iDelete.setTypeface(font);
viewHolder.iAddQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
product.setOrderQuantity(product.getOrderQuantity() + 1);
product.setOrderPrice(product.getOrderQuantity() * product.getPrice_max());
itemClickListener.onItemClick(productList);
notifyDataSetChanged();
}
});
viewHolder.iMinusQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
product.setOrderQuantity(product.getOrderQuantity() - 1);
product.setOrderPrice(product.getOrderQuantity() * product.getPrice_max());
if (product.getOrderQuantity() == 0) {
createAndShowAlertDialog(position, productList);
} else {
itemClickListener.onItemClick(productList);
notifyDataSetChanged();
}
}
});
viewHolder.iDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createAndShowAlertDialog(position, productList);
notifyDataSetChanged();
}
});
return view;
}
private void createAndShowAlertDialog(final int position, final ArrayList<Product> productList) {
AlertDialog.Builder builder = new AlertDialog.Builder(context,R.style.MyDialogTheme);
builder.setTitle("Are you sure you want to delete " + productList.get(position).getProduct_name());
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
productList.remove(position);
itemClickListener.onItemClick(productList);
notifyDataSetChanged();
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
productList.get(position).setOrderQuantity(1);
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
// add items into spinner
public void addItemsOnSDiscountAndPreselect(ViewHolder viewHolder, int discount) {
List<Integer> list = new ArrayList<Integer>();
for(int index = 0; index <= 100; index++) {
list.add(index);
}
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.sDiscount.setAdapter(dataAdapter);
int spinnerPosition = dataAdapter.getPosition(discount);
viewHolder.sDiscount.setSelection(spinnerPosition);
}
private class SpinnerListener implements AdapterView.OnItemSelectedListener {
private int mSpinnerPosition;
private DiscountSpinnerListener discountSpinnerListener;
private ViewHolder viewHolder;
public SpinnerListener(ViewHolder viewHolder, int spinnerPosition, DiscountSpinnerListener discountSpinnerListener) {
mSpinnerPosition = spinnerPosition;
this.discountSpinnerListener = discountSpinnerListener;
this.viewHolder = viewHolder;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
float spinnerValue = Float.parseFloat(arg0.getItemAtPosition(arg2).toString());
float discount = 1.0f - (spinnerValue/100.0f);
float totalItemPrice = productList.get(mSpinnerPosition).getPrice_max() * productList.get(mSpinnerPosition).getOrderQuantity() * discount;
productList.get(mSpinnerPosition).setOrderPrice(totalItemPrice);
productList.get(mSpinnerPosition).setDiscount_per_item(Integer.parseInt(arg0.getItemAtPosition(arg2).toString()));
// Listener to set total price of an item after discount
discountSpinnerListener.onDiscountChange(viewHolder.tvQtyPrice, mSpinnerPosition, totalItemPrice);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
P/S: Please ignore the calculation to get the discount price first, as it does conflict against my both discount spinner(initially I was only implementing the discount per item).
This is screenshot of my app: See here
You are using orderList in your adapter but have you update your orderList after calculating the discount?
if you dont update the data in orderList , notifyDataSetChangeddoesnt really do anything.
hope that helps.

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

Categories