I have issue that when I click to increase quantity of position first item and when I scolling down and up then, position of that item is flickering...
Please help me out guys thanks in advance
This is my adapter class.
package growcia.malacus.com.growcia.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import growcia.malacus.com.growcia.R;
import growcia.malacus.com.growcia.activity.ProductListActivity;
import growcia.malacus.com.growcia.database.SqliteDatabaseClass;
import growcia.malacus.com.growcia.model.SellerProductPOJO;
public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.ViewHolder> {
public Context context;
SqliteDatabaseClass DB;
String productCode;
boolean isPressed = false;
int count = 0;
int qty;
public String pname, price, img_path;
static int productItem = 0;
int totPrice;
ProductListActivity objProductList;
List<SellerProductPOJO> productListDetails;
public ProductListAdapter(List<SellerProductPOJO> productDetails, Context context) {
super();
DB = new SqliteDatabaseClass(context);
objProductList = new ProductListActivity();
this.productListDetails = productDetails;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_product, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final SellerProductPOJO objSellerProductPOJO = productListDetails.get(position);
try {
JSONArray jar = DB.getAllProductCodeAndQtyProductList();
Log.e("total pid and qty ad : ", "" + jar.toString());
for (int i = 0; i < jar.length(); i++) {
JSONObject job = jar.getJSONObject(i);
String cart_productId = job.getString("ProductCode");
String productQty = job.getString("QuantityOrdered");
Log.e("id and qty: ", cart_productId + " qty: " + productQty);
String plist_prod_id = productListDetails.get(position).getProductCode();
Log.e("product id in cart : ", "" + cart_productId.toString());
Log.e("product id service : ", "" + plist_prod_id.toString());
}
} catch (JSONException J) {
J.printStackTrace();
}
String url = objSellerProductPOJO.getImagePath();
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder) // optional
.error(R.drawable.error) // optional
.resize(100, 100) // optional
.into(holder.ivProduct);
holder.tvProductName.setText(objSellerProductPOJO.getProductName());
holder.tvUnit.setText(objSellerProductPOJO.getAvailableQuantity());
holder.tvPrice.setText(objSellerProductPOJO.getPrice());
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/abc.ttf");
holder.tvProductName.setTypeface(font);
holder.tvUnit.setTypeface(font);
holder.tvPrice.setTypeface(font);
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
holder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SellerProductPOJO objSellerProduct = productListDetails.get(position);
String stock = holder.tvUnit.getText().toString();
int qtyMiddle = Integer.parseInt(holder.tvQty.getText().toString());
int qtyStock = Integer.parseInt(objSellerProduct.getAvailableQuantity().toString());
if (!stock.equalsIgnoreCase("0")) {
if (qtyMiddle < qtyStock) {
pname = objSellerProduct.getProductName();
img_path = objSellerProduct.getImagePath();
price = objSellerProduct.getPrice();
productCode = objSellerProduct.getProductCode();
String str_qty = holder.tvQty.getText().toString();
int qty = Integer.parseInt(str_qty);
qty = qty + 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty() + "");
int reduceable_stock = qtyStock - qty;
holder.tvUnit.setText(reduceable_stock + "");
if (qty > 0) {
boolean entryStatus = DB.Exists(productCode);
if (entryStatus) {
productItem = productItem + 1;
String str_newQty = holder.tvQty.getText().toString();
int newqty = Integer.parseInt(str_newQty);
double intPrice = Double.parseDouble(price);
double totPrice = qty * intPrice;
DB.updateProductQty(productCode, newqty, totPrice);
totPrice = DB.getSumPrice();
Log.e("all price update: ", "" + totPrice);
} else {
productItem = 1;
DB.addProductItem(productCode, pname, img_path, productItem, price, price);
}
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
}
} else {
Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
}
}
}
});
holder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stock = holder.tvUnit.getText().toString();
if (!stock.equalsIgnoreCase("0")) {
SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);
String str_qty = holder.tvQty.getText().toString();
int qty = Integer.parseInt(str_qty);
if (qty != 0) {
int qtyStockMinusClick = Integer.parseInt(holder.tvUnit.getText().toString());
holder.tvUnit.setText((qtyStockMinusClick + 1) + "");
Log.e("btnMinus", "" + qty);
if (qty == 1) {
Log.e("", "inside 0 qty");
DB.delete_byID(productCode);
qty = qty - 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty()+"");
} else {
qty = qty - 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty()+"");
double intPrice = Double.parseDouble(price);
double totPrice = qty * intPrice;
DB.updateProductQty(productCode, qty, totPrice);
}
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
}
} else {
Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
}
});
holder.imagefavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("position", "all position" + position);
if (isPressed)
holder.imagefavorite.setBackgroundResource(R.drawable.ic_not_favourite);
else
holder.imagefavorite.setBackgroundResource(R.drawable.favourite_icon);
isPressed = !isPressed;
}
});
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return productListDetails.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvProductName;
public TextView tvUnit;
public TextView tvPrice;
public TextView tvQty;
public ImageView ivProduct;
public ImageView imagefavorite;
// public EditText edqntiry;
public Button btnPlus;
public Button btnMinus;
public ViewHolder(View itemView) {
super(itemView);
ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvUnit = (TextView) itemView.findViewById(R.id.tvUnit);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
tvQty = (TextView) itemView.findViewById(R.id.tvQty);
btnPlus = (Button) itemView.findViewById(R.id.btnPlus);
btnMinus = (Button) itemView.findViewById(R.id.btnMinus);
imagefavorite = (ImageView) itemView.findViewById(R.id.imagefavorite);
}
}
}
When I am going to incerase qty then below screen shows
when I am scrolled down and up then below screen shows
You are not setting the initial value of holder.tvQty in your onBindViewHolder method.
When you update the value of holder.tvQty in holder.btnPlus or holder.btnMinus listeners, you should save that value somewhere in your objSellerProductPOJO:
objSellerProductPOJO.setQty(final_str_qty)
Then under:
holder.tvPrice.setText(objSellerProductPOJO.getPrice());
add:
holder.tvQty.setText(objSellerProductPOJO.getQty());
You need to update the productListDetails variable on add or subtract after
holder.tvQty.setText(final_str_qty);
And notify the adapter using notifydatasetchange()
In your onClick() methods, replace the the position parameter of the onBindViewHolder() method with the getAdapterPosition().
Replace from
SellerProductPOJO objSellerProduct = productListDetails.get(position);
SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);
to
SellerProductPOJO objSellerProduct = productListDetails.get(getAdapterPosition());
SellerProductPOJO objSellerProductDeduct = productListDetails.get(getAdapterPosition());
Related
i have a cartactivity and cartadapter, in cartadapter i add increment and decrement for each stuff, and i sum it in total price and total weight and send it to activity ( it worked by passing textview activity from cartactivity to adapteractivity ) and now i want to get seperated quantity for each item to send to database with format Example if item is ( Wallet, Bag, Shoes ) then quanitity that will send to database like this ( 2, 3, 3) 2 represent for wallet and (,) for seperating item quantity, 3 represent bag, and 3 represent shoes. i don't know how to take each quantity and send it in a format like that
have a look on my adapter
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import app.gify.co.id.R;
import app.gify.co.id.activity.List_Kado;
import app.gify.co.id.modal.MadolCart;
public class AdapterCart extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<MadolCart> carts;
MadolCart mm;
View view;
View viewku;
Context context;
int kuantitas;
String totalname;
int totalBerat, totalharga;
TextView totalhargas, totalberats;
public AdapterCart(ArrayList<MadolCart> carts, Context context, TextView totalhargas, TextView totalberats) {
this.carts = carts;
this.context = context;
this.totalhargas = totalhargas;
this.totalberats = totalberats;
}
public class MyCart extends RecyclerView.ViewHolder {
public ImageView gambar, tambah, kurang;
public TextView harga, nama, quantitas;
public RelativeLayout background, foreground;
public ElegantNumberButton quantity;
public MyCart(#NonNull View itemView) {
super(itemView);
gambar = itemView.findViewById(R.id.gambarcart);
tambah = itemView.findViewById(R.id.tambahcart);
kurang = itemView.findViewById(R.id.kurangcart);
harga = itemView.findViewById(R.id.hargacart);
nama = itemView.findViewById(R.id.namacart);
quantitas = itemView.findViewById(R.id.quantitas);
background = itemView.findViewById(R.id.background);
foreground = itemView.findViewById(R.id.foreground);
quantity = itemView.findViewById(R.id.quantity);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart, parent, false);
viewku = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart, parent, false);
return new MyCart(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
kuantitas = carts.get(position).getJumlah();
int hargaku = carts.get(position).getHarga() * kuantitas;
for (int a = 0; a < carts.size(); a++){
Log.d("cartsizeku", "onBindViewHolder: " + carts.size()+ " s " + carts.get(a).getNamacart() + " s " + carts.get(a).getHarga());
String nama = carts.get(position).getNamacart();
if (nama.equals(carts.get(a).getNamacart())){
totalhargas.setText(String.valueOf(totalCart(carts, carts.get(a).getNamacart())));
totalberats.setText(String.valueOf(beratCart(carts, carts.get(a).getNamacart())));
}
}
Locale locale = new Locale("id", "ID");
NumberFormat format = NumberFormat.getCurrencyInstance(locale);
((MyCart)holder).harga.setText(format.format(Double.valueOf(hargaku)));
((MyCart)holder).nama.setText(carts.get(position).getNamacart());
Glide.with(view).load(carts.get(position).getGambar()).into(((MyCart)holder).gambar);
Intent intent = new Intent("message_subject_intent");
// intent.putExtra("name", String.valueOf((totalCart(carts))));
intent.putExtra("title", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
((MyCart) holder).tambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart) holder).quantitas.getText().toString());
if (count<9){
count+=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(totalCart(carts, nama)));
totalberats.setText(String.valueOf(beratCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
((MyCart) holder).kurang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = Integer.parseInt(((MyCart)holder).quantitas.getText().toString());
if (count>1){
count-=1;
((MyCart)holder).quantitas.setText(String.valueOf(count));
int harga = carts.get(position).getHarga()*count;
((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
String nama = carts.get(position).getNamacart();
totalhargas.setText(String.valueOf(kurangtotalcart(carts, nama)));
totalberats.setText(String.valueOf(kurangberatCart(carts, nama)));
}
// ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
int total = hargaku * kuantitas;
Intent intents = new Intent("message_subject_intent");
intents.putExtra("name", String.valueOf((getName(carts))));
LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
}
});
}
#Override
public int getItemCount() {
return carts.size();
}
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
public int beratCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat += items.get(i).getBerat();
}
}
return totalBerat;
}
public int kurangberatCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalBerat -= items.get(i).getBerat();
}
}
return totalBerat;
}
public String getName(List<MadolCart> name){
String ku = "";
for (int i = 0; i < name.size(); i++){
ku += name.get(i).getNamacart() + ", ";
}
return ku;
}
public void removeItem(int item){
carts.remove(item);
notifyItemRemoved(item);
}
public void restoreItem(MadolCart madolCart, int item){
carts.add(item, madolCart);
notifyItemInserted(item);
}
public void quantityPlus(MadolCart madolCart, int item){
}
}
and this is my activity
package app.gify.co.id.activity;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.google.android.material.navigation.NavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import java.util.Random;
import app.gify.co.id.R;
import app.gify.co.id.adapter.AdapterCart;
import app.gify.co.id.modal.MadolCart;
//import app.gify.co.id.thirdparty.GMailSender;
//import app.gify.co.id.thirdparty.SenderAgent;
import app.gify.co.id.widgets.RecyclerTouchDelete;
import static app.gify.co.id.baseurl.UrlJson.DELETECART;
import static app.gify.co.id.baseurl.UrlJson.GETBARANG;
import static app.gify.co.id.baseurl.UrlJson.GETCART;
public class CartActivity extends AppCompatActivity implements RecyclerTouchDelete.RecyclerTouchListener{
Button Checkout, lanjutBelanja;
ImageView backCart;
TextView totalbelanjar, totalberat;
AdapterCart adapterCart;
ArrayList<MadolCart> madolCarts;
String namacart, gambarcart, uidku;
GridLayoutManager glm;
RecyclerView recyclerView;
MainActivity mainActivity;
NavigationView navigationView;
public int hargaku, beratku, kuantitas, lastNumber, idbarang, getHargaAwal;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Spanned templateConvert;
NumberFormat format;
Locale id;
Random random;
String template, idberat, idharga;
private Dialog dialog;
LayoutInflater inflater;
ImageView goku;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart);
lanjutBelanja = findViewById(R.id.lanjutBelanjaChart);
lanjutBelanja.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), List_Kado.class);
startActivity(intent);
});
getHargaAwal = getIntent().getIntExtra("harga", 0);
Log.d("setHarga", getHargaAwal + "");
dialog = new Dialog(CartActivity.this);
inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.loading, null);
goku = layout.findViewById(R.id.custom_loading_imageView);
goku.animate().rotationBy(360).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.setCancelable(false);
dialog.setContentView(layout);
dialog.show();
id = new Locale("id", "ID");
format = NumberFormat.getCurrencyInstance(id);
random = new Random();
lastNumber = 0;
for (int k = 0; k < 3; k++){
lastNumber+=(random.nextInt(10)*Math.pow(10, k));
}
backCart = findViewById(R.id.backCartNav);
backCart.setOnClickListener(v -> finish());
Checkout = findViewById(R.id.checkoutChart);
totalbelanjar = findViewById(R.id.totalBelanjaChart);
totalberat = findViewById(R.id.totalBeratChart);
recyclerView = findViewById(R.id.rvChart);
preferences = PreferenceManager.getDefaultSharedPreferences(CartActivity.this);
uidku = preferences.getString("uid", "");
madolCarts = new ArrayList<>();
getCart();
glm = new GridLayoutManager(CartActivity.this, 1);
recyclerView.setLayoutManager(glm);
Checkout.setOnClickListener(view -> {
Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
intent.putExtra("idharga", idharga);
intent.putExtra("name", namacart);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = preferences.edit();
editor.remove("range");
editor.remove("acara");
editor.remove("buat");
editor.apply();
startActivity(intent);
});
LocalBroadcastManager.getInstance(this).registerReceiver(passValue, new IntentFilter("message_subject_intent"));
ItemTouchHelper.SimpleCallback callback = new RecyclerTouchDelete(0, ItemTouchHelper.LEFT, this);
new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
private String replaceNumberOfAmount(String original, int replace){
return original.substring(0, original.length() - 3) + replace;
}
// private void senderEmail(){
// SenderAgent senderAgent = new SenderAgent("gify.firebase#gmail.com", "Confirmation Transaction Gify", templateConvert, CartActivity.this);
// senderAgent.execute();
// }
private void getCart(){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETCART, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String id_tetap = object.getString("id_tetap");
if (id_tetap.equalsIgnoreCase(uidku)){
kuantitas = object.getInt("jumlah");
idbarang = object.getInt("id_barang");
idharga = object.getString("harga");
idberat = object.getString("berat");
getBerat(idbarang);
dialog.dismiss();
}
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("getcart", "getCart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
public BroadcastReceiver passValue = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
namacart = intent.getStringExtra("name");
Log.d("hargalast", namacart + "");
namacart = intent.getStringExtra("title");
template = "<h2> Gify Transaction </h2> " +
"<h3> Kamu baru saja melakukan pesanan dengan detail sebagai berikut </h3>"
+ "<p><b> Nama barang: </p></b>"
+ "<p><b> Harga barang" + format.format(Double.valueOf(replaceNumberOfAmount(idharga, lastNumber))) + ". Silahkan transfer dengan tiga digit terakhir yaitu :" + lastNumber + "</p></b>"
+ "<p><b> Jika sudah melakukan pembayaran, silahkan konfirmasi disini </p></b>"
+ "https://api.whatsapp.com/send?phone=082325328732&text=Confirmation%20Text"
+ "<h2>Salam, Gify Team</h2>";
Log.d("hargalast", idharga + lastNumber);
templateConvert = Html.fromHtml(template);
}
};
private void getBerat(int idbarang){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG, null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
int id_barang = object.getInt("id");
if (idbarang==id_barang){
String gambar = object.getString("photo");
int harga = object.getInt("harga");
String namacart = object.getString("nama");
int berat = object.getInt("berat");
MadolCart madolCart = new MadolCart(gambar, harga, namacart, idbarang, kuantitas, berat);
madolCarts.add(madolCart);
adapterCart = new AdapterCart(madolCarts, CartActivity.this, totalbelanjar, totalberat);
recyclerView.setAdapter(adapterCart);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Log.d("jsoner", "getBerat: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
#Override
public void onSwipe(RecyclerView.ViewHolder viewHolder, int dir, int pos) {
if (viewHolder instanceof AdapterCart.MyCart){
String name = madolCarts.get(viewHolder.getAdapterPosition()).getNamacart();
MadolCart madolCart = madolCarts.get(viewHolder.getAdapterPosition());
int deleteIndex = viewHolder.getAdapterPosition();
Log.d("taptap", "onSwipe: " + madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
GETBARANG(madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());
adapterCart.removeItem(viewHolder.getAdapterPosition());
}
}
private void deletecart(String id_barang){
StringRequest stringRequest = new StringRequest(Request.Method.GET, DELETECART+"?idtetap="+uidku+"&idbarang="+id_barang, response -> {
try {
if (response.equalsIgnoreCase("bisa")){
Toast.makeText(CartActivity.this, "Barang telah di hapus", Toast.LENGTH_SHORT).show();
Log.d("bisabarangcart", "GETBARANG: " );
}
}catch (Exception e){
Log.d("ekscartactivity", "deletecart: " + e.getMessage());
}
}, error -> {
Log.d("ernocartdel", "deletecart: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(stringRequest);
}
private void GETBARANG(String namas){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG,null, response -> {
try {
JSONArray array = response.getJSONArray("YukNgaji");
for (int a = 0; a < array.length(); a++){
JSONObject object = array.getJSONObject(a);
String nama = object.getString("nama");
if (nama.equalsIgnoreCase(namas)){
Log.d("namabarang", "GETBARANG: " + nama + " s " + namas);
String id = object.getString("id");
deletecart(id);
}
}
}catch (Exception e){
Log.d("barangexce", "GETBARANG: " + e.getMessage());
}
}, error -> {
Log.d("errorgetbrng", "GETBARANG: " + error.getMessage());
});
RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
queue.add(objectRequest);
}
}
to make sum of total prices i used this code
public int totalCart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga += items.get(i).getHarga();
}
}
return totalharga;
}
i put summing code in a method, and call the method on if button + is clicked
if button - is clicked it will call this method
public int kurangtotalcart(ArrayList<MadolCart> items, String name){
for(int i = 0 ; i < items.size(); i++) {
totalname = items.get(i).getNamacart();
if (totalname.equals(name)){
totalharga -= items.get(i).getHarga();
}
}
return totalharga;
}
and now idk how to get seperated quanitity for each position / item in recycler view then send it to activity as format ( 1, 2, 3) (,) mean a seperator for each item
How to get value seperated quantity from recycler view item position?
SOLVED
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}
I found the solution by adding this:
public String getSeperatedquantity(List<MadolCart> quantity){
String kus = "";
for (int i = 0; i < quantity.size(); i++){
kus += quantity.get(i).getQuantity() + ", ";
}
return kus;
}
My app is an attendance for students; I create a list of the students and when I click on the student's name the picture must be checked.
The problem is when I scroll down I see other students get checked too.
`public class attendanceAdapter extends RecyclerView.Adapter{
private List<MyStudentsModel> studentsModels;
private AttendanceModel attModels;
private List<String> attList;
private Context context;
private DatabaseReference present, mr7laCount;
private String date = "1/6/2018";
public attendanceAdapter(Context context, List<MyStudentsModel> studentsModels){
this.context = context;
this.studentsModels = studentsModels;
}
#NonNull
#Override
public StudentAttHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_single_student_att_view,parent,false);
StudentAttHolder studentAttHolder = new StudentAttHolder(view);
attModels = new AttendanceModel();
attList = new ArrayList<>();
present = FirebaseDatabase.getInstance().getReference("Attendance");
mr7laCount = FirebaseDatabase.getInstance().getReference("AllCount");
return studentAttHolder;
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final StudentAttHolder holder, int position) {
final String split[] = date.split("/");
final MyStudentsModel student = studentsModels.get(position);
holder.stu_name.setText(student.getFirstName() +" "+ student.getSecondName());
if (student.getServedImage().equals("0") | student.getServedImage() == null){
Glide.with(context).load(R.drawable.daria).into(holder.stu_img);
}else {
Glide.with(context)
.load(Uri.parse(student.getServedImage()))
.into(holder.stu_img);
}
final String id = student.getSid();
holder.stu_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.stu_tgb.toggle();
if(holder.stu_tgb.isChecked()){
attList.add(id);
String date = split[2] + "x" + split[1] + "x" + split[0];
String dateM = split[2] + "/" + split[1] + "/" + split[0];
int total = getItemCount();
int absence = total - attList.size();
attModels.setDay(dateM);
attModels.setPresence(String.valueOf(attList.size()));
attModels.setAbsence(String.valueOf(absence));
attModels.setTotal(String.valueOf(total));
present
.child("Served")
.child(student.getAlmar7la())
.child(student.getAlfasl())
.child(split[0])
.child(split[1])
.child(split[2])
.setValue(attList);
mr7laCount
.child("Served")
.child(student.getAlmar7la())
.child(String.valueOf(date))
.child(student.getAlfasl())
.setValue(attModels);
} else {
attList.remove(id);
String date = split[2] + "x" + split[1] + "x" + split[0];
String dateM = split[2] + "/" + split[1] + "/" + split[0];
int total = getItemCount();
int absence = total - attList.size();
attModels.setDay(dateM);
attModels.setPresence(String.valueOf(attList.size()));
attModels.setAbsence(String.valueOf(absence));
attModels.setTotal(String.valueOf(total));
present
.child("Served")
.child(student.getAlmar7la())
.child(student.getAlfasl())
.child(split[0])
.child(split[1])
.child(split[2])
.setValue(attList);
if(attList.size() == 0){
mr7laCount
.child("Served")
.child(student.getAlmar7la())
.child(String.valueOf(date))
.child(student.getAlfasl())
.removeValue();
}else {
mr7laCount
.child("Served")
.child(student.getAlmar7la())
.child(String.valueOf(date))
.child(student.getAlfasl())
.setValue(attModels);
}
}
}
});
}
#Override
public int getItemCount() {
return studentsModels.size();
}
final public class StudentAttHolder extends RecyclerView.ViewHolder{
ImageView stu_img;
TextView stu_name;
ToggleButton stu_tgb;
public StudentAttHolder(View itemView) {
super(itemView);
stu_name = itemView.findViewById(R.id.student_name_att);
stu_img = itemView.findViewById(R.id.student_image_att);
stu_tgb = itemView.findViewById(R.id.student_toggleButton);
}
}
}
`
when I checked Faustino Hausner
I saw Wilber Bainbridge and Hester Barley checked too
I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.
Main goal: android app-messendger for chating with company support.
Task: To impliment timers of waiting response from operator or client in listview.
Trouble: In all listview items rendering one of all timer, and then application is listing some timers for a moment are rendering for correctly result, but when they are overlap.
Visually you can see here: https://drive.google.com/file/d/0B_SjoeZavdZwdXlUQlU3QTVKeG8/view?usp=sharing]1
Code:
public class SessionAdapter extends BaseAdapter {
private static final String TAG = SessionAdapter.class.toString();
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private List<ViewHolder> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining(currentTime, 0);
}
}
}
};
public SessionAdapter(List<SessionInterface> sessions, Context context) {
this.sessions = sessions;
this.context = context;
lstHolders = new ArrayList<>();
startUpdateTimer();
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
#Override
public int getCount() {
return sessions.size();
}
#Override
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
Log.d(TAG, "getPositionById-i: " + i);
Log.d(TAG, "getPositionById-id: " + id);
Log.d(TAG, "getPositionById-sessionId: " + sessionId);
boolean eq = id == sessionId;
Log.d(TAG, "getPositionById-sessionId==id: " + eq);
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SessionInterface session = sessions.get(position);
ViewHolder holder;
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.adapter_sessions, null);
holder.label = (TextView) convertView.findViewById(R.id.label);
holder.sessionTitle = (TextView) convertView.findViewById(R.id.ticket_title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.message = (TextView) convertView.findViewById(R.id.comment);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.chatStatusImage = (ImageView) convertView.findViewById(R.id.ticket_status);
holder.timeRemaining = (TextView) convertView.findViewById(R.id.time_remaining);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
Date jud = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru")).parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
holder.updateTimeRemaining(System.currentTimeMillis(), milliseconds);
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed(convertView);
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting(convertView);
} else {
holder.setOperatorWaiting(convertView);
}
}
return convertView;
}
private class ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public void updateTimeRemaining(long currentTime, long timeAgo) {
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) ((timeDiff / (1000 * 60 * 60)) % 24);
int hourMinutes = hours*60 + minutes;
timeRemaining.setText(hourMinutes + ":" + (seconds < 10 ? "0" + seconds : seconds));
} else {
timeRemaining.setText("Expired!!");
}
}
public void setClosed(View convertView) {
this.status.setText("Закрыто");
this.status.setTextColor(convertView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting(View convertView) {
this.status.setText("Оператор ожидает ваш ответ");
this.status.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting(View convertView) {
this.status.setText("Ожидается ответ оператора");
this.status.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_operator));
}
}
}
Fooh.. year.. It's was realy not easy..
Here is my resolving.. maybe it will help anobody in future..
import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import ru.pinspb.pinsupport.R;
import ru.pinspb.pinsupport.common.Constants;
import ru.pinspb.pinsupport.pojo.Message;
import ru.pinspb.pinsupport.pojo.SessionInterface;
import ru.pinspb.pinsupport.utils.Helpers;
public class SessionAdapter extends RecyclerView.Adapter<SessionAdapter.Holder> {
public interface OnItemClickListener {
void onItemClick(SessionInterface item);
}
private static final String TAG = SessionAdapter.class.toString();
private final OnItemClickListener listener;
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private Handler mHandler = new Handler();
public SessionAdapter(List<SessionInterface> sessions, Context context, OnItemClickListener listener) {
this.sessions = sessions;
this.context = context;
this.listener = listener;
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
public int getCount() {
return sessions.size();
}
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_sessions, null);
return new Holder(v);
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final SessionInterface session = sessions.get(position);
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
holder.bind(session, listener);
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
SimpleDateFormat ru = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru"));
ru.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
Date jud = ru.parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
final long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
startUpdateTimer(new Runnable() {
#Override
public void run() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow"));
Date currentDate = calendar.getTime();
holder.updateTimeRemaining(currentDate.getTime(), milliseconds);
}
});
// Log.d(TAG, "Sid: " + session.getId() + " ;\nnow: " + System.currentTimeMillis() + ";\n last date: " + mLastMessage.getDate() + "; \nmill: " + milliseconds );
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed();
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting();
} else {
holder.setOperatorWaiting();
}
}
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
#Override
public int getItemCount() {
return sessions.size();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
boolean eq = id == sessionId;
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer(final Runnable runnable) {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(runnable);
}
}, 1000, 1000);
}
public static class Holder extends RecyclerView.ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public Holder(View itemView) {
super(itemView);
this.label = (TextView) itemView.findViewById(R.id.label);
this.sessionTitle = (TextView) itemView.findViewById(R.id.ticket_title);
this.date = (TextView) itemView.findViewById(R.id.date);
this.message = (TextView) itemView.findViewById(R.id.comment);
this.status = (TextView) itemView.findViewById(R.id.status);
this.chatStatusImage = (ImageView) itemView.findViewById(R.id.ticket_status);
this.timeRemaining = (TextView) itemView.findViewById(R.id.time_remaining);
}
public void updateTimeRemaining(long currentTime, long timeAgo) {
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
long seconds = TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff));
String time = String.format("%d:%s",
TimeUnit.MILLISECONDS.toMinutes(timeDiff),
seconds < 10 ? seconds + "0" : String.valueOf(seconds)
);
timeRemaining.setText(time);
}
public void setClosed() {
this.status.setText("closed");
this.status.setTextColor(itemView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_operator));
}
public void bind(final SessionInterface item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
when i click + button increment the price and click - button decrease the price it's work perfectly but when i scroll listview the value of tvPrices (TextView) is changed.
What should i do for the stay increment price?
here is my adapter
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
price.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
try {
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
ShowHashMapValue();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In onclick, after you decrement the value call notifyDataSetChanged()
notifyDataSetChanged
but its a costly operation, since it refreshes complete list