Calling calculation function in adapter class to java class? - java

I have Cart activity where user can add,update and delete their cart. Each of the function has it owns java activity and I also have CartAdapter activity. I want to perform a calculation that can display the total price of customer item in the ViewCart activity. I did the calculation on CartAdapter but I have a problem with displaying the totalPrice inside my ViewCart activity.
I got error that said
java.lang.NumberFormatException: For input string: "99.00"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.valueOf(Integer.java:801)
at com.example.g.Customer.CartAdapter.onBindViewHolder(CartAdapter.java:68)
at com.example.g.Customer.CartAdapter.onBindViewHolder(CartAdapter.java:28)
Here is my CartAdapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Cart> CartList;
int totalPrice = 0;
int totalPrice1 = 0;
public CartAdapter(ArrayList<Cart> CartListList) {
this.CartList = CartListList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cust_view_cart, viewGroup, false);
context = viewGroup.getContext();
return new CartAdapter.MyViewHolder(view);
}
#NonNull
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
Picasso.with(context).load(CartList.get(i).getPro_image()).into(myViewHolder.image);
myViewHolder.name.setText(CartList.get(i).getPro_name());
myViewHolder.category.setText(CartList.get(i).getPro_category());
myViewHolder.price.setText(CartList.get(i).getPro_price());
myViewHolder.size.setText(CartList.get(i).getSize());
myViewHolder.quantity.setText(CartList.get(i).getQuantity());
totalPrice1 = (int)Double.parseDouble((CartList.get(i).getPro_price())) * Integer.valueOf(CartList.get(i).getQuantity());
totalPrice = totalPrice + totalPrice1;
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cart_id = CartList.get(i).getCart_id();
String keyB = CartList.get(i).getBrand_id();
String pid = CartList.get(i).getPro_id();
String cust_id = CartList.get(i).getCust_id();
String name = CartList.get(i).getPro_name();
String category = CartList.get(i).getPro_category();
String price = CartList.get(i).getPro_price();
String image = CartList.get(i).getPro_image();
String size = CartList.get(i).getSize();
String quantity = CartList.get(i).getQuantity();
Intent intent = new Intent(context, UpdateCart.class);
intent.putExtra("cust_id", cust_id);
intent.putExtra("Cart_id", cart_id);
intent.putExtra("keyB", keyB);
intent.putExtra("pid", pid);
intent.putExtra("pro_name", name);
intent.putExtra("pro_category", category);
intent.putExtra("pro_price", price);
intent.putExtra("pro_image", image);
intent.putExtra("size", size);
intent.putExtra("quantity", quantity);
context.startActivity(intent);
}
});
myViewHolder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pro_name = CartList.get(i).getPro_name();
String cart_id = CartList.get(i).getCart_id();
String cust_id = CartList.get(i).getCust_id();
DatabaseReference dbCart = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
dbCart.child(cart_id).removeValue();
//set url of image to storageref
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(CartList.get(i).getPro_image());
// Delete the file
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Uh-oh, an error occurred!
}
});
//Toolbar
// Remove the item on remove/button click
CartList.remove(i);
/*
Parameters
position : Position of the item that has now been removed
*/
notifyItemRemoved(i);
/*
Parameters
positionStart : Position of the first item that has changed
itemCount : Number of items that have changed
*/
notifyItemRangeChanged(i, CartList.size());
// Show the removed item label
Toast.makeText(context, pro_name + " has been removed from your cart", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return CartList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name, category, price, size, quantity;
ImageView image, btnDelete;
public MyViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
category = itemView.findViewById(R.id.category);
image = itemView.findViewById(R.id.image);
price = itemView.findViewById(R.id.price);
size = itemView.findViewById(R.id.size);
quantity = itemView.findViewById(R.id.quantity);
btnDelete = itemView.findViewById(R.id.delete);
}
}
}
ViewCart
public class ViewCart extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
FirebaseUser currentUser;
ArrayList<Cart> CartList;
RecyclerView recyclerView;
private int totalPrice = 0;
TextView total;
private String userID, cust_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_cart);
total = findViewById(R.id.total);
total.setText( String.valueOf(totalPrice));
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
userID = currentUser.getUid();
cust_id = firebaseAuth.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartList.add(ds.getValue(Cart.class));
}
CartAdapter cartAdapter = new CartAdapter(CartList);
recyclerView.setAdapter(cartAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
openDialog();
}
private void openDialog() {
LoginDialog loginlDialog = new LoginDialog();
loginlDialog.show(getSupportFragmentManager(), "login dialog");
}

use this
public class ViewCart extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
FirebaseUser currentUser;
ArrayList<Cart> CartList;
RecyclerView recyclerView;
private int totalPrice = 0;
TextView total;
private String userID, cust_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_cart);
total = findViewById(R.id.total);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
userID = currentUser.getUid();
cust_id = firebaseAuth.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("Cart").child(cust_id);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
CartList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CartList.add(ds.getValue(Cart.class));
Cart cart = ds.getValue(Cart.class);
totalPrice = totalPrice + (int)Double.parseDouble(cart.getPrice()) * Integer.valueOf(cart.getQuantity());
}
CartAdapter cartAdapter = new CartAdapter(CartList);
recyclerView.setAdapter(cartAdapter);
total.setText( String.valueOf(totalPrice));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
openDialog();
}
private void openDialog() {
LoginDialog loginlDialog = new LoginDialog();
loginlDialog.show(getSupportFragmentManager(), "login dialog");
}

Why have you kept price as String , instead of float or int?
You probably have kept price as String so that you can display it in TextView, but with this you are forced to cast it every time.
You should keep price as float and to set it as text in TextView simply use string concatenation :
float price = 99.00;
textView.setText(value+ "");

Related

Deletion of Node is not working in Firebase Realtime Database in Android Java

I am making an application in which products are inserted into the database and I am inserting the 1 product once. it is working fine. But when I delete a specific node/ product from Database. deletion code is also working fine but at the same time product is again adding into the database.
Main Fragment Code;
public class Products_fragment extends Fragment {
FloatingActionButton fab_addproduct;
RecyclerView recyclerView;
EditText searchview;
BottomSheetDialog bottomSheetDialog;
FirebaseDatabase firebaseDatabase;
ArrayList<Product_model> DatabaseProductlist;
FirebaseAuth auth;
CircularDotsLoader ProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products_fragment, container, false);
setviews(view);
setInitilization();
setclicks();
setadapter();
return view;
}
private void setInitilization() {
DatabaseProductlist = new ArrayList<>();
}
private void setadapter() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
DatabaseReference reference = database.getReference("Users").child(UID).child("Products");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ProgressBar.setVisibility(View.GONE);
DatabaseProductlist.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Product_model model = dataSnapshot.getValue(Product_model.class);
DatabaseProductlist.add(model);
}
Product_Adapter product_adapter = new Product_Adapter(DatabaseProductlist);
recyclerView.setAdapter(product_adapter);
product_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(), error.getMessage());
}
});
}
private void setclicks() {
fab_addproduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog = new BottomSheetDialog(getContext(), R.style.AppBottomSheetDialogTheme);
bottomSheetDialog.setContentView(R.layout.productadd_bottom_sheet);
TextInputEditText product_id = bottomSheetDialog.findViewById(R.id.product_id);
TextInputEditText product_name = bottomSheetDialog.findViewById(R.id.product_name);
TextInputEditText product_quantity = bottomSheetDialog.findViewById(R.id.product_quantity);
MaterialButton add_btn = bottomSheetDialog.findViewById(R.id.add_btn);
TextInputEditText product_price = bottomSheetDialog.findViewById(R.id.product_price);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(product_name.getText()).toString().isEmpty() || product_id.getText().toString().isEmpty() || product_price.getText().toString().isEmpty() || product_quantity.getText().toString().isEmpty()) {
ToastUtility.showErrorToast(getContext(), "Please Fill all Fields");
} else {
Product_model model = new Product_model(Integer.parseInt(product_id.getText().toString()), Integer.parseInt(product_quantity.getText().toString()), Integer.parseInt(product_price.getText().toString()), product_name.getText().toString());
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Users");
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
reference.child(UID).child("Products").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(product_name.getText().toString().trim()).exists()) {
ToastUtility.showErrorToast(getContext(),"Product Already Exists!");
}
else{
reference.child(UID).child("Products").child(product_name.getText().toString().trim()).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
ToastUtility.showSuccessToast(getContext(),"Successfully Added");
setadapter();
}
else{
ToastUtility.showErrorToast(getContext(), Objects.requireNonNull(task.getException()).getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(),error.getMessage());
}
});
}
}
});
bottomSheetDialog.show();
}
});
}
private void setviews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
fab_addproduct = view.findViewById(R.id.fab_addproduct);
searchview = view.findViewById(R.id.searchview);
ProgressBar = view.findViewById(R.id.progressbar);
}
}
Adapter Code:
public class Product_Adapter extends RecyclerView.Adapter<Product_Adapter.myviewholder> {
ArrayList<Product_model> dataholder;
public Product_Adapter(ArrayList<Product_model> dataholder) {
this.dataholder = dataholder;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow_product, parent, false);
return new myviewholder(view); }
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.idtv.setText("" + dataholder.get(position).getId());
holder.pnametv.setText("" + dataholder.get(position).getProduct_name());
holder.pqtytv.setText("" + dataholder.get(position).getProduct_quantity());
holder.ppritv.setText("" + dataholder.get(position).getProduct_price());
holder.delimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
FirebaseUser curUser = FirebaseAuth.getInstance().getCurrentUser();
assert curUser != null;
String UID = curUser.getUid();
String productname = dataholder.get(holder.getAdapterPosition()).getProduct_name();
DatabaseReference reference = db.getReference("Users").child(UID).child("Products");
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
notifyItemRemoved(holder.getAdapterPosition());
}
else
{
ToastUtility.showErrorToast(view.getContext(),"Product is not deleting ");
}
}
});
}
});
}
#Override
public int getItemCount() {
return dataholder.size();
}
static class myviewholder extends RecyclerView.ViewHolder{
TextView idtv, pnametv, pqtytv, ppritv, delimg, edit_img;
public myviewholder(#NonNull View itemView) {
super(itemView);
idtv = itemView.findViewById(R.id.idtv);
pnametv = itemView.findViewById(R.id.pnametv);
pqtytv = itemView.findViewById(R.id.pqtytv);
ppritv = itemView.findViewById(R.id.ppritv);
delimg = itemView.findViewById(R.id.delimg);
edit_img = itemView.findViewById(R.id.edit_img);
}
}
}
When you click delete, shouldn't you remove your item from the list before notifying data changed:
//this code belongs to the part where you click the delete
.........
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
//here remove the item from your list
dataholder.remove(holder.getAdapterPosition());
//then notify the adapter
notifyItemRemoved(holder.getAdapterPosition());
}

Always null value passed from fragment to adapter

I have a recycler view on my home page which is showing some posts from my db. I'm passing data like userID, username etc., into the adapter but the profile picture URL is always null inside the adapter. If I try to print it inside the fragment it shows the correct value.
My database structure:
PostRecyclerAdapter:
public class PostRecyclerAdapter extends RecyclerView.Adapter<PostRecyclerAdapter.ViewHolder> {
List<PostModel> postList;
Context context;
final private DatabaseReference postRef = FirebaseDatabase.getInstance().getReference("posts");
final private DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference("likes");
final private DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
public PostRecyclerAdapter(ArrayList<PostModel> postModelArrayList, Context context) {
this.postList = postModelArrayList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// check if post is liked or not
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
// check if current post is liked from this user
if (snapshot.child(holder.id).hasChild(user.getUid())) {
// post is liked form this user
holder.like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
} else {
// post is not liked from this user
holder.like_btn.setImageResource(R.drawable.ic_thump_up_outline);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();
}
});
// Get current post id set username, authorID, profile picture URL, likes and post image URL
holder.id = postList.get(position).getId();
holder.username.setText(postList.get(position).getName());
holder.userID = postList.get(position).getAuthorID();
holder.like_counter_tv.setText(postList.get(position).getLikes());
Glide.with(context).load(postList.get(position).getImgUrl()).into(holder.postImg);
// Load profile picture
String profilePictureUrl = postList.get(position).getProfileImgUrl();
// profilePictureUrl IS ALWAYS NULL
if (profilePictureUrl != null) {
if (!profilePictureUrl.equals("none")) {
Glide.with(context).load(profilePictureUrl).into(holder.profileImage);
}
}
}
#Override
public int getItemCount() {
return postList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
CardView container;
String id;
TextView username, like_counter_tv;
ImageView postImg;
ImageButton like_btn;
CircleImageView profileImage;
boolean isLiked = false;
String userID;
public void updateLikes(String postID, boolean isNotLiked) {
postRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
String currentLikesToString = snapshot.child(postID).child("likes").getValue().toString();
int currentLikesToInt = Integer.parseInt(currentLikesToString);
if (isNotLiked) {
int newCurrentLikes = currentLikesToInt + 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
} else {
int newCurrentLikes = currentLikesToInt - 1;
String newCurrentLikesToString = Integer.toString(newCurrentLikes);
// Update likes on Real-time DB
postRef.child(postID).child("likes").setValue(newCurrentLikesToString);
// update likes on TextView
like_counter_tv.setText(newCurrentLikesToString);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(context, "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
}
public ViewHolder(#NonNull View itemView) {
super(itemView);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
final ConstraintLayout sContainer = itemView.findViewById(R.id.second_container);
profileImage = itemView.findViewById(R.id.user_profile_image);
container = itemView.findViewById(R.id.post_item_container);
username = itemView.findViewById(R.id.post_username);
postImg = itemView.findViewById(R.id.post_image);
like_btn = itemView.findViewById(R.id.likeBtn);
like_counter_tv = itemView.findViewById(R.id.like_counter);
likeRef.keepSynced(true);
profileImage.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
if (snap.child("name").getValue().toString().equals(username.getText().toString())) {
UserProfileActivity.username = username.getText().toString();
UserProfileActivity.userID = snap.child("id").getValue().toString();
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(context, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
context.startActivity(intent);
});
sContainer.setOnLongClickListener(v -> {
FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();
PostOptionsDialog optionsDialog = new PostOptionsDialog();
optionsDialog.setPostId(id);
if (username.getText().toString().equals(user.getDisplayName())) {
optionsDialog.setAuthor(true);
} else {
optionsDialog.setAuthor(false);
}
optionsDialog.show(manager, "options");
return false;
});
like_btn.setOnClickListener(v -> {
// animate like button when clicked
YoYo.with(Techniques.Shake)
.duration(500)
.repeat(0)
.playOn(like_btn);
isLiked = true;
likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (isLiked) {
if (snapshot.child(id).hasChild(user.getUid())) {
// post is liked from this user, so user wants to unlike this post
like_btn.setImageResource(R.drawable.ic_thump_up_outline);
likeRef.child(id).child(user.getUid()).removeValue();
isLiked = false;
Toast.makeText(context, "You unliked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, false);
} else {
// post is not liked from ths user, so the user wants to like this post
like_btn.setImageResource(R.drawable.ic_thumb_up_filled);
likeRef.child(id).child(user.getUid()).setValue("true");
Toast.makeText(context, "You liked this meme!", Toast.LENGTH_SHORT).show();
// update likes to DB
updateLikes(id, true);
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(itemView.getContext(), "Error: " + error, Toast.LENGTH_LONG).show();
}
});
});
}
}
}
HomeFragment:
public class HomeFragment extends Fragment {
LoadingDialog progressDialog;
final DatabaseReference postsRef = FirebaseDatabase.getInstance().getReference("posts");
final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
final RecyclerView recyclerView = view.findViewById(R.id.home_recycler_view);
final ArrayList<PostModel> postModelArrayList = new ArrayList<>();
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
final RecyclerView.Adapter recyclerAdapter = new PostRecyclerAdapter(postModelArrayList, getContext());
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
progressDialog = LoadingDialog.Companion.get(getActivity());
progressDialog.show();
postsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
progressDialog.hide();
for (DataSnapshot snap : snapshot.getChildren()) {
PostModel postModel = new PostModel();
postModel.setId(snap.child("id").getValue(String.class));
postModel.setImgUrl(snap.child("imgUrl").getValue(String.class));
postModel.setLikes(snap.child("likes").getValue(String.class));
postModel.setName(snap.child("name").getValue(String.class));
// find user id and set profile picture by name
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot snap1 : snapshot1.getChildren()) {
if (snap1.child("name").getValue(String.class).equals(snap.child("name").getValue(String.class))) {
postModel.setAuthorID(snap1.child("id").getValue(String.class));
postModel.setProfileImgUrl(snap1.child("profileImgUrl").getValue(String.class));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
postModelArrayList.add(postModel);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(getContext(), "Error: " + error, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}

Can't convert object of type java.lang.String to type (Firebase,RecyclerView)

I got two RecyclerView on the same page at this moments which are Breakfast and Lunch RecyclerView but I am facing the following error Can't convert object of type java.lang.String to type com.example
It highlights this line
userRecordslist.add(ds.getValue(UserRecordsModel.class));
I have tried several ways.
but when I used this code , the data from different record was displayed in the Breakfast RecyclerView
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
these are the screenshots of my Firebase and my App. You can see both data from different record is displayed on the same RecyclerView.
and later I tried to use this "new" code for database reference, the data that was supposedly retrieved from Firebase was NOT be displayed on the Breakfast Recycler View and I got the Can't convert object of type java.lang.String to type error
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("BreakfastRecord");
I want to fetch the data and display it in the "suppose" RecyclerView. Please help out.
This code for my PlanMeal activity:
//BUTTON
Button backBtn;
Button addMealBreakBtn;
Button addMealLunchBtn;
Button addMealDinnerBtn;
//DATABASE
FirebaseAuth mAuth;
FirebaseUser currentUser;
DatabaseReference userRecordRef, myRef,requiredCalorieRef, mylunchRef;
//TEXT VIEW
TextView userRequiredCalorie;
ArrayList<UserRecordsModel> userRecordslist;
RecyclerView recyclerView, recyclerViewlunch;
private RecyclerView.Adapter userRecordHolder;
//DATE
String date_record ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_meal_user);
date_record = new SimpleDateFormat("yyMMdd", Locale.getDefault()).format(new Date());
//create a date string.
String date_n = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(new Date());
//get hold of textview.
TextView date = (TextView) findViewById(R.id.datePlanMeal);
//set it as current date.
date.setText(date_n);
//INI VIEWS
userRequiredCalorie= (TextView) findViewById(R.id.outputPlanMealCalorie);
//FIREBASE AUTH
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
//DATABASE REFERENCE
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
/*mylunchRef=FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("LunchRecord");*/
//myRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//mylunchRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//RECYCLER VIEW
//*********BREAKFAST******************************************//
recyclerView = findViewById(R.id.userRecordRecylerView);
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
//*********LUNCH******************************************//
recyclerViewlunch = findViewById(R.id.userRecordRecylerViewLunch);
LinearLayoutManager manager1 = new LinearLayoutManager(this);
recyclerViewlunch.setLayoutManager(manager1);
recyclerViewlunch.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerViewlunch.setAdapter(userRecordHolder);
//BUTTON
addMealBreakBtn = (Button) findViewById(R.id.addMealBreakBtn);
backBtn = (Button)findViewById(R.id.backBtnPlan) ;
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
/*String userCalorieSuggestion = Double.toString((Double) dataSnapshot.child("daily calorie").getValue());
showDailyCalorie.setText(("Daily Calorie Suggestion: " + userCalorieSuggestion +"kcal"));*/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//BACK BUTTON*************************************************
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,HomepageUser.class);
startActivity(signIn);
}
});
//ADD MEAL BUTTONS**********************************************
addMealBreakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent breakfast = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(breakfast);
}
});
addMealLunchBtn = (Button) findViewById(R.id.addMealLunchBtn);
addMealLunchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct_Lunch.class);
startActivity(signIn);
}
});
addMealDinnerBtn = (Button) findViewById(R.id.addMealDinnerBtn);
addMealDinnerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(signIn);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (myRef != null) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userRecordslist = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userRecordslist.add(ds.getValue(UserRecordsModel.class));
}
UserRecordsHolder userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(PlanMealUser.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
This is my Model :
package com.example.buddymealplanneruser.Child.UserRecords;
public class UserRecordsModel {
private String foodName;
private String foodCalorie;
//constructor
public UserRecordsModel (String foodName,
String foodCalorie
)
{
this.foodName = foodName;
this.foodCalorie = foodCalorie;
}
public UserRecordsModel(){
}
//Getter and Setter
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodCalorie() {
return foodCalorie;
}
public void setFoodCalorie(String foodCalorie) {
this.foodCalorie = foodCalorie;
}
}
This is my Adapter
public class UserRecordsHolder extends RecyclerView.Adapter<UserRecordsHolder.MyURHolder> {
Context context;
ArrayList<UserRecordsModel> userRecordslist;
public UserRecordsHolder (ArrayList<UserRecordsModel> userRecordslist)
{
this.userRecordslist=userRecordslist;
}
#NonNull
#Override
public MyURHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_user_records, viewGroup,false);
return new MyURHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyURHolder myURHolder, int i) {
myURHolder.foodName.setText(userRecordslist.get(i).getFoodName());
myURHolder.foodCalorie.setText(userRecordslist.get(i).getFoodCalorie());
}
#Override
public int getItemCount()
{
return userRecordslist.size();
}
class MyURHolder extends RecyclerView.ViewHolder
{
TextView foodName, foodCalorie;
public MyURHolder (#NonNull View itemView){
super(itemView);
foodName = itemView.findViewById(R.id.userRecordsFName);
foodCalorie = itemView.findViewById(R.id.userRecordsKcal);
}
}
}
Hope someone can help.
You'll need one more level beneath BreakfastRecord or LunchRecord:
UserRecords
UID
Date
BreakfastRecord
1
foodCalorie
foodName
2
foodCalorie
foodName
3
foodCalorie
foodName

RecyclerView shows the same item many times in my app

I've created a match system in my Android program that also includes a chat section which has 2 fragments. The first fragment shows your chats, the second one shows your matches by using RecyclerView and UsersAdapter. However, in the second (match) fragment, people who you matched with are shown many times. For example, the same person is seen many times as you can see here.
My code is below.
UserFragment:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UsersAdapter usersAdapter;
private List<User> mUsers;
FirebaseFirestore usersfragmentstore;
FirebaseAuth readauth;
DocumentReference readref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
usersfragmentstore = FirebaseFirestore.getInstance();
readauth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_users, container, false);
readref = usersfragmentstore.collection("users").document(readauth.getCurrentUser().getUid());
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
UserAdapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
String theLastMessage;
public UsersAdapter(Context mContext, List<User> mUsers, boolean ischat) {
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_chat, parent, false);
return new UsersAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = mUsers.get(position);
holder.username.setText(user.getName());
if (user.getImageURL().equals("default")) {
holder.profile_image.setImageResource(R.drawable.profilepicture);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat) {
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat) {
if (user.getStatus().equals("online")) {
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.chatusername);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg) {
theLastMessage = "defalut";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) || chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage) {
case "default":
last_msg.setText("No message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
What am I missing?
befor adding new data first clear list by mUsers.clear(); as below
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
mUsers.clear();
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}

How to get key from firebase using RecyclerView

I can get key and show in Log.d but it don't show in RecyclerView. What's wrong with it?
HistoryActivity.java it contains my recyclerView:
public class HistoryActivity extends AppCompatActivity {
FirebaseFirestore mFirestore;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
RecyclerView mHisList;
ArrayList<PreviousLst> history;
adt_rv_HisList adtRvHisList;
TextView ptName;
TextView ptPort;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
getSupportActionBar().setSubtitle("History");
Intent it = getIntent();
String patName = it.getStringExtra("nm");
String patID = it.getStringExtra("idpat");
String portNum = it.getStringExtra("pNum");
String regisDate = it.getStringExtra("rdate");
ptName = findViewById(R.id.txName);
ptPort = findViewById(R.id.portpassValue);
ptName.setText(patName);
ptPort.setText(portNum);
history = new ArrayList<>();
setupRecyclerView();
setupFireBase();
loadDataFromDatabase(portNum);
}
private void setupFireBase() {
mFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
private void setupRecyclerView() {
mHisList = findViewById(R.id.rv_prev_lst);
mHisList.setHasFixedSize(true);
mHisList.setLayoutManager(new LinearLayoutManager(this));
mHisList.setAdapter(adtRvHisList);
}
public void loadDataFromDatabase(String portNum) {
if(history.size()>0)
history.clear();
DatabaseReference myRef;
DatabaseReference passref;
switch (portNum){
case "Huang-Yai0002":
String p2 = "NETEKG-Huang-Yai0002";
myRef = database.getReference("MACHINE");
passref = myRef.child(p2).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(keydate);
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
case "Huang-Yai0003":
String p3 = "NETEKG-Huang-Yai0003";
myRef = database.getReference("MACHINE");
passref = myRef.child(p3).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(postSnapshot.getKey());
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
default:
Log.d(TAG, "Value is: " + portNum);
Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
break;
}
}
}
adt_rv_HisList.java Adapter:
public class adt_rv_HisList extends RecyclerView.Adapter<adtrvHisListViewHolder> {
HistoryActivity historyActivity;
ArrayList<PreviousLst> history;
public adt_rv_HisList(HistoryActivity historyActivity, ArrayList<PreviousLst> history) {
this.history = history;
this.historyActivity = historyActivity;
}
#NonNull
#Override
public adtrvHisListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(historyActivity.getBaseContext()).inflate(R.layout.hislist_item, viewGroup, false);
return new adtrvHisListViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adtrvHisListViewHolder holder, int position) {
holder.hdate.setText(history.get(position).getHisDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView();
}
});
}
private void dialogView() {
final Dialog dia = new Dialog(historyActivity);
dia.setContentView(R.layout.dialog_ask_view);
dia.show();
Button pvgraph = (Button)dia.findViewById(R.id.bt_pvgraph);
Button pvhr = (Button)dia.findViewById(R.id.bt_pvhrate);
Button cc = (Button)dia.findViewById(R.id.btn_cancel);
cc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
}
});
pvgraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewgraphActivity.class);
historyActivity.startActivity(it);
}
});
pvhr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewHRActivity.class);
historyActivity.startActivity(it);
}
});
}
#Override
public int getItemCount() {
return 0;
}
}
adtrvHisListViewHolder.java Contains the ViewHolder :
public class adtrvHisListViewHolder extends RecyclerView.ViewHolder {
public TextView hdate;
public adtrvHisListViewHolder(View itemView) {
super(itemView);
hdate = itemView.findViewById(R.id.his_date);
}
}
PreviousLst.java is Model class for my recyclerView:
public class PreviousLst {
String HisDate;
public PreviousLst(String HisDate){
this.HisDate = HisDate;
}
public PreviousLst(){
}
public String getHisDate() {
return HisDate;
}
public void setHisDate(String hisDate) {
HisDate = hisDate;
}
}
This is my key that I get and show in Log.d
D/ContentValues: Child are: HEART RATE
D/ContentValues: Child are:LEAD 1
Child are: LEAD 2
Child are: LEAD 3
Child are: LEAD 4
Child are: LEAD 5
Child are: LEAD 6
but it don't shoe in App.
enter image description here
#Override
public int getItemCount() {
//return 0;
replace it with history.size();
}
the added lines tells the adapter how many items, the adapter has to bind the items to the recycler view. By default it is 0, means the adapter class will never call the binView method to show the items at view side

Categories