I'm having a RecyclerView. when an item is clicked, those values will be displayed in a dialog box. So now I want those values to be passed to it's activity. Below is my code.
Below is my adapter class. Here I have a variable called (availstockTv). I need this variable to be passed to my activity class.
Adapter class:
package com.shopping.grocery_ekart.Adapters;
public class AdapterProductUser extends RecyclerView.Adapter<AdapterProductUser.HolderProductUser> implements Filterable {
private Context context;
public ArrayList<ModelProduct> productsList, filterList;
private FilterProductUser filter;
public AdapterProductUser(Context context, ArrayList<ModelProduct> productsList) {
this.context = context;
this.productsList = productsList;
this.filterList = productsList;
}
@NonNull
@Override
public HolderProductUser onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_todaydeal, parent, false);
return new HolderProductUser(view);
}
@Override
public void onBindViewHolder(@NonNull HolderProductUser holder, int position) {
ModelProduct modelProduct = productsList.get(position);
String productTitle = modelProduct.getProductTitle();
String productQuantity = modelProduct.getProductQuantity();
String notinStock = modelProduct.getNotinStock();
String stockValue = modelProduct.getStockValue();
holder.titleTv.setText(productTitle);
if (notinStock.equals("true")) {
holder.stockTv.setVisibility(View.VISIBLE);
} else {
holder.stockTv.setVisibility(View.GONE);
}
holder.addToCartTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (notinStock.equals("true")) {
Toast.makeText(context, "Product out of stock, can't add to cart", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Please select Quantity", Toast.LENGTH_SHORT).show();
showQuantityDialog(modelProduct);
}
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (notinStock.equals("true")) {
Toast.makeText(context, "Product out of stock", Toast.LENGTH_SHORT).show();
}else {
showQuantityDialog(modelProduct);
}
}
});
}
private double cost;
private int finalCost;
private int quantity = 0;
public int availability;
private void showQuantityDialog(ModelProduct modelProduct) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_quantity, null);
TextView titleTv = view.findViewById(R.id.titleTv);
TextView pQuantityTv = view.findViewById(R.id.pQuantityTv);
ImageButton decrementBtn = view.findViewById(R.id.decrementBtn);
TextView quantityTv = view.findViewById(R.id.quantityTv);
ImageButton incrementBtn = view.findViewById(R.id.incrementBtn);
Button continueBtn = view.findViewById(R.id.continueBtn);
TextView availstockTv = view.findViewById(R.id.availstockTv);
String title = modelProduct.getProductTitle();
String productQuantity = modelProduct.getProductQuantity();
String availableStock = modelProduct.getProductStock();
final String price;
cost = Double.parseDouble(price.replaceAll("₹", ""));
finalCost = Integer.parseInt(price.replaceAll("₹", ""));
quantity = 1;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
try{
Picasso.get().load(image).placeholder(R.drawable.cart).into(productIv);
}catch (Exception e){
productIv.setImageResource(R.drawable.cart);
}
titleTv.setText(""+title);
pQuantityTv.setText(""+productQuantity);
availstockTv.setText(availableStock);
quantityTv.setText(""+quantity);
AlertDialog dialog = builder.create();
dialog.show();
continueBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = titleTv.getText().toString().trim();
String quantity = quantityTv.getText().toString().trim();
//addToCart(productId, title, priceEach, totalPrice, quantity);
dialog.dismiss();
}
});
}
@Override
public int getItemCount() {
return productsList.size();
}
class HolderProductUser extends RecyclerView.ViewHolder{
private ImageView productIconIv;
private TextView discountedNoteTv, brandTv, addToCartTv,
discountedPriceTv, originalPriceTv, stockTv, dealTv;
public TextView titleTv;
private RelativeLayout Rl1;
public HolderProductUser(@NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
discountedNoteTv = itemView.findViewById(R.id.discountedNoteTv);
titleTv = itemView.findViewById(R.id.titleTv);
brandTv = itemView.findViewById(R.id.brandTv);
addToCartTv = itemView.findViewById(R.id.addToCartTv);
discountedPriceTv = itemView.findViewById(R.id.discountedPriceTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
stockTv = itemView.findViewById(R.id.stockTv);
dealTv = itemView.findViewById(R.id.dealTv);
Rl1 = itemView.findViewById(R.id.Rl1);
}
}
}
Activity class:
package com.shopping.grocery_ekart.Activities;
public class ShopDetailsActivity extends AppCompatActivity {
private static final String cod = "Cash on Delivery";
private static final String op = "Online Payment";
private ImageView shopIv;
private TextView TabTodayDealTv, TabAllProductsTv, shopNameTv, phoneTv, emailTv, openCloseTv, deliveryFeeTv, filterTv,
addressTv, filteredProductsTv, cartCountTv, dummy;
private ImageButton callBtn, mapBtn, cartBtn, backBtn, filterProductBtn, reviewBtn, filterBtn;
private EditText searchProductEt;
private RecyclerView productsRv, todayDealRv;
private RelativeLayout todayDealRL, productsRl;
private RatingBar ratingBar;
private String shopUid;
private String myLatitude, myLongitude, myPhone;
private String shopName, shopEmail, shopPhone, shopAddress, shopLatitude, shopLongitude;
public String deliveryFee;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private ProgressDialog progressDialog;
private ArrayList<ModelProduct> productsList;
private AdapterProductUser adapterProductUser;
private ArrayList<ModelCartItem> cartItemList;
private AdapterCartItem adapterCartItem;
private ArrayList<ModelProduct> productList;
private AdapterProductAdmin adapterProductAdmin;
private EasyDB easyDB;
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;
private Dialog dialog1, dialog2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_details);
shopIv = findViewById(R.id.shopIv);
shopNameTv = findViewById(R.id.shopNameTv);
phoneTv = findViewById(R.id.phoneTv);
emailTv = findViewById(R.id.emailTv);
openCloseTv = findViewById(R.id.openCloseTv);
deliveryFeeTv = findViewById(R.id.deliveryFeeTv);
addressTv = findViewById(R.id.addressTv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
callBtn = findViewById(R.id.callBtn);
mapBtn = findViewById(R.id.mapBtn);
cartBtn = findViewById(R.id.cartBtn);
backBtn = findViewById(R.id.backBtn);
filterProductBtn = findViewById(R.id.filterProductBtn);
searchProductEt = findViewById(R.id.searchProductEt);
productsRv = findViewById(R.id.productsRv);
cartCountTv = findViewById(R.id.cartCountTv);
reviewBtn = findViewById(R.id.reviewBtn);
filterBtn = findViewById(R.id.filterBtn);
filterTv = findViewById(R.id.filterTv);
ratingBar = findViewById(R.id.ratingBar);
dummy = findViewById(R.id.dummy);
productsRl = findViewById(R.id.productsRl);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
shopUid = getIntent().getStringExtra("shopUid");
firebaseAuth = FirebaseAuth.getInstance();
GridLayoutManager layoutManager=new GridLayoutManager(this,2);
productsRv.setLayoutManager(layoutManager);
easyDB = EasyDB.init(this, "ITEMS_DB")
.setTableName("ITEMS_TABLE")
.addColumn(new Column("Item_Id", new String[]{"text", "unique"}))
.addColumn(new Column("Item_PID", new String[]{"text", "not null"}))
.addColumn(new Column("Item_Name", new String[]{"text", "not null"}))
.addColumn(new Column("Item_Price_Each", new String[]{"text", "not null"}))
.addColumn(new Column("Item_Price", new String[]{"text", "not null"}))
.addColumn(new Column("Item_Quantity", new String[]{"text", "not null"}))
.doneTableColumn();
cartCount();
filterBtn.setVisibility(View.GONE);
filterTv.setVisibility(View.GONE);
dialog1 = new Dialog(this);
dialog1.setContentView(R.layout.checkout_warning_dialog);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog1.getWindow().setBackgroundDrawable(getDrawable(R.drawable.custom_dialog));
}
dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog1.setCancelable(false); //Optional
dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //Setting the animations to dialog
Button continue_shop = dialog1.findViewById(R.id.continue_shop);
continue_shop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog1.dismiss();
}
});
dialog2 = new Dialog(this);
dialog2.setContentView(R.layout.paymentmode_dialog);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog2.getWindow().setBackgroundDrawable(getDrawable(R.drawable.custom_dialog));
}
dialog2.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog2.setCancelable(false); //Optional
dialog2.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //Setting the animations to dialog
backBtn = dialog2.findViewById(R.id.backBtn);
Button clear = dialog2.findViewById(R.id.clear);
Button pay_now = dialog2.findViewById(R.id.pay_now);
Button place_order = dialog2.findViewById(R.id.place_order);
RadioGroup radioGroup = dialog2.findViewById(R.id.groupradio);
RadioButton radia_id1 = dialog2.findViewById(R.id.radia_id1);
RadioButton radia_id2 = dialog2.findViewById(R.id.radia_id2);
TextView status = dialog2.findViewById(R.id.status);
radioGroup.clearCheck();
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
radioGroup.clearCheck();
pay_now.setVisibility(View.INVISIBLE);
place_order.setVisibility(View.INVISIBLE);
status.setVisibility(View.INVISIBLE);
dialog2.dismiss();
}
});
pay_now.setVisibility(View.INVISIBLE);
place_order.setVisibility(View.INVISIBLE);
status.setVisibility(View.INVISIBLE);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton radia_id2 = dialog2.findViewById(R.id.radia_id2);
RadioButton radia_id1 = dialog2.findViewById(R.id.radia_id1);
if (radia_id1.isChecked()) {
pay_now.setVisibility(View.VISIBLE);
place_order.setVisibility(View.GONE);
status.setVisibility(View.VISIBLE);
status.setText(op);
dummy.setText(op);
}
if (radia_id2.isChecked()) {
place_order.setVisibility(View.VISIBLE);
pay_now.setVisibility(View.GONE);
status.setVisibility(View.VISIBLE);
status.setText(cod);
dummy.setText(cod);
}
}
});
pay_now.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(ShopDetailsActivity.this, "Please select any one option", Toast.LENGTH_SHORT).show();
}
else {
RadioButton radia_id2 = (RadioButton)radioGroup.findViewById(selectedId);
submitOrder();
}
}
});
place_order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == -1) {
Toast.makeText(ShopDetailsActivity.this, "Please select any one option", Toast.LENGTH_SHORT).show();
}
else {
RadioButton radia_id1 = (RadioButton)radioGroup.findViewById(selectedId);
submitOrder();
deleteCartData();
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId != -1) {
radioGroup.clearCheck();
pay_now.setVisibility(View.INVISIBLE);
place_order.setVisibility(View.INVISIBLE);
status.setVisibility(View.INVISIBLE);
}
else {
Toast.makeText(ShopDetailsActivity.this, "No option is selected", Toast.LENGTH_SHORT).show();
}
}
});
}
private void deleteCartData() {
easyDB.deleteAllDataFromTable(); //delete all records from cart
}
public void cartCount() {
//keep it public so we can access in adapter
//get cart count
int count = easyDB.getAllData().getCount();
if (count <= 0) {
//no item in cart, hide cart count textview
cartCountTv.setVisibility(View.GONE);
} else {
//have items in cart, show cart count textview and set count
cartCountTv.setVisibility(View.VISIBLE);
cartCountTv.setText("" + count); //concatenate with string bcz we cant set integer in text view
}
}
checkOutBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (allTotalPrice<1) {
dialog1.show();
}
else {
dialog2.show();
}
}
});
}
public String quantity, name;
private void submitOrder() {
progressDialog.setMessage("Placing order...");
progressDialog.show();
final String timestamp = "" + System.currentTimeMillis();
String cost = allTotalPriceTv.getText().toString().trim().replace("₹", "");// remove ₹ if contains
String paystatus = dummy.getText().toString();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("orderId", ""+timestamp);
hashMap.put("orderTime", ""+timestamp);
hashMap.put("orderStatus", "In Progress"); //In Progress/Completed/Cancelled
hashMap.put("orderCost", ""+cost);
hashMap.put("orderBy", ""+firebaseAuth.getUid());
hashMap.put("orderTo", ""+shopUid);
hashMap.put("latitude", ""+myLatitude);
hashMap.put("longitude", ""+myLongitude);
hashMap.put("PaymentMode", ""+paystatus);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(shopUid).child("Orders");
ref.child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//order info added now add order items
for (int i = 0; i < cartItemList.size(); i++) {
String pId = cartItemList.get(i).getpId();
String id = cartItemList.get(i).getId();
String cost = cartItemList.get(i).getCost();
name = cartItemList.get(i).getName();
String price = cartItemList.get(i).getPrice();
quantity = cartItemList.get(i).getQuantity();
HashMap<String, String> hashMap1 = new HashMap<>();
hashMap1.put("pId", pId);
hashMap1.put("name", name);
hashMap1.put("cost", cost);
hashMap1.put("price", price);
hashMap1.put("quantity", quantity);
ref.child(timestamp).child("Items").child(pId).setValue(hashMap1);
}
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "Please wait.....", Toast.LENGTH_SHORT).show();
prepareNotificationMessage(timestamp);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//failed placing order
progressDialog.dismiss();
Toast.makeText(ShopDetailsActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadShopProducts() {
//init list
productsList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(shopUid).child("Products")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//clear list before adding item
productsList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productsList.add(modelProduct);
}
//setup adapter
adapterProductUser = new AdapterProductUser(ShopDetailsActivity.this, productsList);
//set adapter
productsRv.setAdapter(adapterProductUser);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void prepareNotificationMessage(String orderId) {
//which user place order , send notification to admin
//prepare data for notification
String NOTIFICATION_TOPIC = "/topics/" + category_Constants.FCM_TOPIC;
String NOTIFICATION_TITLE = "New Order "+ orderId;
String NOTIFICATION_MESSAGE = "Your customer has placed a new order!";
String NOTIFICATION_TYPE = "NewOrder";
//prepare json (what and where to send)
JSONObject notificationJo = new JSONObject();
JSONObject notificationBodyJo = new JSONObject();
try {
//what to send
notificationBodyJo.put("notificationType", NOTIFICATION_TYPE);
notificationBodyJo.put("buyerUid", firebaseAuth.getUid());
notificationBodyJo.put("sellerUid", shopUid);
notificationBodyJo.put("orderId", orderId);
notificationBodyJo.put("notificationTitle", NOTIFICATION_TITLE);
notificationBodyJo.put("notificationMessage", NOTIFICATION_MESSAGE);
//where to send
notificationJo.put("to", NOTIFICATION_TOPIC);
notificationJo.put("data", notificationBodyJo);
}
catch (Exception e) {
Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
sendFcmNotification(notificationJo, orderId);
}
private void sendFcmNotification(JSONObject notificationJo, String orderId) {
//send volley request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//after sending fcm, start order details activity
//after placing order open order details page
Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
intent.putExtra("orderTo", shopUid);
intent.putExtra("orderId", orderId);
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//if failed sending fcm, still start order details activity
// Intent intent = new Intent(ShopDetailsActivity.this, OrdersDetailsUsersActivity.class);
// intent.putExtra("orderTo", shopUid);
// intent.putExtra("orderId", orderId);
//startActivity(intent);
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
//put required headers
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "key=" + category_Constants.FCM_KEY);
return headers;
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
}
Ho do I achieve this. Badly need help as I'm running out of time for delivery....... Somebody help me. Thanks in Advance:)