Android List View not dynamically populating from Database - java

I am developing a realtime messaging application. I have gotten as far as the user messages being stored in Firebase Realtime Database. But not able to populate them back into a listview. I have a method called displayMessages() where I want to pull all the messages back from the Database and populate into a ListView. For some reason It is not populating the View and I am not sure why. Anyone able to help.
public class ChatRoom extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText input;
private FloatingActionButton fab;
private FirebaseListAdapter<Comment> adapter;
#SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
fab = findViewById(R.id.fab);
input = findViewById(R.id.input);
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
assert userID != null;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
assert user != null;
String userName = user.getUserName();
createMessage(userName);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
}
});
displayMessages();
}
public void createMessage(final String userName) {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().isEmpty()) {
Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
} else {
Date date = new Date();
String currentDateTime = dateFormat.format(date);
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
Comment comment = new Comment(input.getText().toString(), userName,userID,currentDateTime);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Chat").push().setValue(comment).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChatRoom.this, "Message Saved", Toast.LENGTH_SHORT).show();
input.setText("");
displayMessages();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatRoom.this, "Error Occurred: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
//I am able to write new messages to firebase realtime database
//I need to fix this method and populate the list with the messages from the database
public void displayMessages() {
Query query = FirebaseDatabase.getInstance().getReference().child("Chat");
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Comment> options =
new FirebaseListOptions.Builder<Comment>()
.setQuery(query, Comment.class)
.setLayout(R.layout.message)
.build();
adapter = new FirebaseListAdapter<Comment>(options){
#Override
protected void populateView(#NotNull View v, #NotNull Comment model, int position) {
TextView messageText = v.findViewById(R.id.message_text);
TextView messageUser = v.findViewById(R.id.message_user);
TextView messageTime = v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(model.getDateTime());
}
};
listOfMessages.setAdapter(adapter);
}
}

Related

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;
}
}

Android ImageView null object when trying to set Image

I am having difficulty setting an ImageView with a string download url that is in a user object that came from the firebase storage DB. The method setImage() is saying the Imageview is a null object and this is true as I have tried to debug it and it comes up as null. How can I resolve this. I think it has something to do with the anonymous inner class.
public class DashBoard extends AppCompatActivity {
private FirebaseAuth mAuth;
private ArrayList<String> motivatingMessages;
private Button gymLocations, profile,health;
public ImageView profileImageView;
private TextView welcome;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProfilePicture();
profileImageView = findViewById(R.id.personalProfile);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
setContentView(R.layout.activity_dash_board);
//getSupportActionBar().setTitle("Welcome To Bodify");
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user != null) {
welcome.setText("User Logged in: ");
welcome.append(user.getUserName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
gymLocations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), GymsNearMe.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PersonalProfile.class));
}
});
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DashBoard.this,Health.class));
}
});
}
public void showProfilePicture() {
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
String image = user.getmImageUrl();
setImage(image);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setImage(String image) {
Picasso.get().load(image).into(profileImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logOut) {
mAuth.signOut();
startActivity(new Intent(getApplicationContext(), LogIn.class));
}
return true;
}
}
enter code here
It looks like you are trying to find the view before inflating the layout:
profileImageView = findViewById(R.id.personalProfile);
move that line after the inflation so after the line:
setContentView(R.layout.activity_dash_board);
In other words, the order of the lines should be:
setContentView(R.layout.activity_dash_board);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
profileImageView = findViewById(R.id.personalProfile);
showProfilePicture();
and you do not need to set the mAuth again in the showProfilePicture
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
profileImageView = findViewById(R.id.personalProfile);
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
showProfilePicture();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
try with this order

Calling calculation function in adapter class to java class?

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+ "");

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

Can't convert object of type java.lang.String to type In DatabaseReferance

I'm building a simple chat application. In user fragment, if we click on user it get crashed and go to previous activity if there is previous chat. While there is no chat with that user fragment works fine, but when we type message and click send message store on Firebase and app crashes, similarly if there is chat, chat fragment get crashed.
I think problem is in mReference.addValueEventListener(new ValueEventListener()) method. Code and error is given below. I saw other answers but didn't understand with my code.
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser mFirebaseUser;
DatabaseReference mDatabaseReference;
ImageView btn_send;
EditText send_msg;
Intent mIntent;
MessageAdapter mMessageAdapter;
List<Chat> mChats;
RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
btn_send = findViewById(R.id.img_btn_send);
send_msg = findViewById(R.id.text_send);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mIntent = getIntent();
final String userid = mIntent.getStringExtra("userid");
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = send_msg.getText().toString();
if (!msg.equals("")){
sendMessage(mFirebaseUser.getUid(), userid, msg);
}
send_msg.setText("");
}
});
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
assert user != null;
username.setText(user.getUsername());
if ( user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher_round);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(profile_image);
}
readMessage(mFirebaseUser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
mDatabaseReference.child("Chats").setValue(hashMap);
}
private void readMessage(final String myId, final String userID, final String imageURL){
mChats = new ArrayList<>();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChats.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Chat chat = dataSnapshot1.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userID) || chat.getReceiver().equals(userID) && chat.getSender().equals(myId)){
mChats.add(chat);
}
mMessageAdapter = new MessageAdapter(MessageActivity.this, mChats, imageURL);
mRecyclerView.setAdapter(mMessageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
ChatsFragment.java
public class ChatsFragment extends Fragment {
private RecyclerView mRecyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
FirebaseUser fUser;
DatabaseReference mReference;
private List<String> userList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chats, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fUser = FirebaseAuth.getInstance().getCurrentUser();
userList = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Chats");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getSender().equals(fUser.getUid())){
userList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fUser.getUid())){
userList.add(chat.getSender());
}
}
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
private void readChats() {
mUsers = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Users");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : userList){
if (user.getId().equals(id)){
if (mUsers.size() != 0){
for ( User user1 : mUsers){
if ( !user.getId().equals(user1.getId()));
mUsers.add(user);
}
}
else{
mUsers.add(user);
}
}
}
}
mUserAdapter = new UserAdapter(getContext(), mUsers);
mRecyclerView.setAdapter(mUserAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Error is :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.4:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.4:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.4:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.4:212)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6228)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

Categories