How to show multiple random childs from Firebase Realtime Database - android

I am trying to show random users from Firebase Realtime Database .I am currently able to show one random user from my Firebase Realtime database but what i want to do is show 6 random users on to my recyclerview at once .But i am unable to figure out how to add query for same without getting an error at runtime.
Mycode
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
ValueEventListener mValueEventListener;
List<String> UserIdsList = new ArrayList<>();
public UsersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
//readUser();
RandomUsers();
return view;
}
private void RandomUsers() {
//mUsers.add((User) UserIdsList);
mUserAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserIdsRef = rootRef.child("UserIds");
ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userIDS = ds.getKey();
UserIdsList.add(userIDS);
}
int UserListSize = UserIdsList.size();
Log.d(TAG, String.valueOf(UserListSize));
Random random=new Random();
int random1=random.nextInt(UserListSize);
// int Rdm= UserIdsList.get(new Random().nextInt(UserListSize));
DatabaseReference UserRef = rootRef.child("Users").child(UserIdsList.get(random1));
Log.d(TAG,"UserRef "+ String.valueOf(UserRef));
//new Random().nextInt(UserListSize)
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException()); //Don't ignore errors!
}
};
UserRef.addListenerForSingleValueEvent(eventListener);
//UserRef.addValueEventListener(eventListener);
Query query2 = UserRef.limitToFirst(2);
query2.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.getMessage()); //Don't ignore errors!
}
};
UserIdsRef.addListenerForSingleValueEvent(mValueEventListener);
//UserIdsRef.addValueEventListener(mValueEventListener);
}
}
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private List<String> UserIdsList;
private boolean ischat;
String theLastMessage;
public UserAdapter(Context mContext, List<User> mUsers,boolean ischat) {
this.mContext = mContext;
this.mUsers = mUsers;
this.ischat=ischat;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
if (user.getImageURL().equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} 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("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
intent.putExtra("ImageURL",user.getImageURL());
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.username);
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 = "default";
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) {
}
});
}
}
Data Snapshot
DataSnapshot { key = KRhmaWXCctMHbU1Z6NAWRGGw2ag2, value = {EmailId=abc#gmail.com, First=shivam} }

You can try this:
DatabaseReference UserRef = rootRef.child("Users").orderByKey().startAt(UserIdsList.get(random1)).lim‌​itToFirst(6);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException());
}
};
UserRef.addListenerForSingleValueEvent(eventListener);

Related

Firebase | How to get the sum of all child entries

The problem when one item value increases the time calculation wrong because the sum value already store. Example: 3 item--- 2+2+2=6 that's right. when 1st item value increases that time 4+2+2=14 (8+previous 6).
Can you help me?
Main focusable part
private void caculatateprice(){
String cccex= uid+"_"+"calculate";
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
int itemTotalPrice = 0;
for (DataSnapshot dataSnapshot : snapshot.child(uid).getChildren()) {
Map<String, Object> tp = (Map<String, Object>) dataSnapshot.getValue();
Object price = tp.get("itemtotalprice");
itemTotalPrice = Integer.parseInt(String.valueOf(price));
subTotal += itemTotalPrice;
finalTotalPrice = subTotal + extraCharge;
subtotal.setText("$" + String.valueOf(subTotal));
deliveryCharge.setText("$" + String.valueOf(extraCharge));
totalPrice.setText("$" + String.valueOf(finalTotalPrice));
}
}
}
java
public class CartFragment extends Fragment {
private RecyclerView recyclerView;
private Button checkOutButton;
private CartItemAdapter itemAdapter;
private ArrayList<CartItemModel> cartItemList;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private FirebaseUser user;
private String uid;
private TextView subtotal,deliveryCharge,totalPrice;
private int subTotal=0,extraCharge=1,finalTotalPrice=0;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recyclerView = view.findViewById(R.id.cartrecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
user = firebaseAuth.getCurrentUser();
uid = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("carts");
GetDataFromFirebase();
checkOutButton = view.findViewById(R.id.checkoutbutton);
subtotal = view.findViewById(R.id.subtotalprice);
deliveryCharge = view.findViewById(R.id.deliveryprice);
totalPrice = view.findViewById(R.id.producttotalprice);
caculatateprice();
}
private void caculatateprice(){
String cccex= uid+"_"+"calculate";
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()) {
int itemTotalPrice = 0;
for (DataSnapshot dataSnapshot : snapshot.child(uid).getChildren()) {
Map<String, Object> tp = (Map<String, Object>) dataSnapshot.getValue();
Object price = tp.get("itemtotalprice");
itemTotalPrice = Integer.parseInt(String.valueOf(price));
subTotal += itemTotalPrice;
finalTotalPrice = subTotal + extraCharge;
subtotal.setText("$" + String.valueOf(subTotal));
deliveryCharge.setText("$" + String.valueOf(extraCharge));
totalPrice.setText("$" + String.valueOf(finalTotalPrice));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void GetDataFromFirebase() {
Query query = databaseReference.child(uid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
CartItemModel productItem = new CartItemModel();
productItem.setImage(snapshot.child("image").getValue().toString());
productItem.setName(snapshot.child("name").getValue().toString());
productItem.setPrice(snapshot.child("price").getValue().toString());
productItem.setProductId(snapshot.child("productId").getValue().toString());
productItem.setQuantity(snapshot.child("quantity").getValue().toString());
productItem.setItemtotalprice(snapshot.child("itemtotalprice").getValue().toString());
cartItemList.add(productItem);
}
itemAdapter = new CartItemAdapter(getActivity(),cartItemList);
recyclerView.setAdapter(itemAdapter);
itemAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if (cartItemList!=null){
cartItemList.clear();
if (itemAdapter!=null){
itemAdapter.notifyDataSetChanged();
}
}
cartItemList = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cart, container, false);
return view;
}
}
Adapter class
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.CartItemViewHolder> {
private int intquantity,itemTotalPrice,itemprice,subTotal,extraCharge=1,finalTotalPrice;
String cartId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("carts").child(cartId);
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("carts");
private Context context;
private ArrayList<CartItemModel> cartItem;
public CartItemAdapter(Context context, ArrayList<CartItemModel> cartItem) {
this.context = context;
this.cartItem = cartItem;
}
#NonNull
#Override
public CartItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item_card, parent, false);
return new CartItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CartItemViewHolder holder, int position) {
String ccc= cartId+"_"+cartItem.get(position).getProductId();
// String cccex= cartId+"_"+"calculate";
holder.itemname.setText(cartItem.get(position).getName());
holder.itemprice.setText("$"+cartItem.get(position).getPrice());
Glide.with(context).load(cartItem.get(position).getImage()).into(holder.itemimage);
holder.quantityitem.setText(cartItem.get(position).getQuantity());
holder.itemtotalprice.setText("$"+cartItem.get(position).getItemtotalprice());
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quantity = cartItem.get(position).getQuantity();
intquantity =Integer.parseInt(quantity.toString());
String itemPrice = cartItem.get(position).getPrice();
itemprice =Integer.parseInt(itemPrice.toString());
if(intquantity>0){
intquantity--;
}
itemTotalPrice = intquantity*itemprice;
HashMap<String, Object> result = new HashMap<>();
result.put("quantity", intquantity);
result.put("itemtotalprice",itemTotalPrice);
databaseReference.child(ccc).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
// subTotal = subTotal+itemTotalPrice;
// finalTotalPrice=subTotal+extraCharge;
// HashMap<String, Object> totalresult = new HashMap<>();
// totalresult.put("subtotal", subTotal);
// totalresult.put("totalprice",finalTotalPrice);
//
// databaseReference1.child(cccex).updateChildren(totalresult)
// .addOnSuccessListener(new OnSuccessListener<Void>() {
// #Override
// public void onSuccess(Void aVoid) {
//
// }
// });
}
});
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quantity = cartItem.get(position).getQuantity();
intquantity =Integer.parseInt(quantity.toString());
String itemPrice = cartItem.get(position).getPrice();
itemprice =Integer.parseInt(itemPrice.toString());
intquantity++;
itemTotalPrice = intquantity*itemprice;
HashMap<String, Object> result = new HashMap<>();
result.put("quantity", intquantity);
result.put("itemtotalprice",itemTotalPrice);
databaseReference.child(ccc).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
// subTotal = subTotal+itemTotalPrice;
// finalTotalPrice=subTotal+extraCharge;
// HashMap<String, Object>totalresult = new HashMap<>();
// totalresult.put("subtotal", subTotal);
// totalresult.put("totalprice",finalTotalPrice);
//
// databaseReference1.child(cccex).updateChildren(totalresult)
// .addOnSuccessListener(new OnSuccessListener<Void>(){
// #Override
// public void onSuccess(Void aVoid){
//
// }
// });
}
});
holder.cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child(ccc).removeValue();
Toast.makeText(context,"Item Removed from Cart",Toast.LENGTH_SHORT).show();
cartItem.remove(position);
notifyItemChanged(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return cartItem.size();
}
public static final class CartItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemname, itemprice, quantityitem, itemtotalprice;
private ImageView itemimage, minus, plus, cross;
public CartItemViewHolder(#NonNull View itemView) {
super(itemView);
itemname = itemView.findViewById(R.id.product_name);
itemprice = itemView.findViewById(R.id.product_price);
itemimage = itemView.findViewById(R.id.product_image);
quantityitem = itemView.findViewById(R.id.itemcount);
itemtotalprice = itemView.findViewById(R.id.itemtotalprice);
minus = itemView.findViewById(R.id.itemminus);
plus = itemView.findViewById(R.id.itemplus);
cross = itemView.findViewById(R.id.itemdelete);
}
}
}
database
{
"carts" : {
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2" : {
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1002" : {
"id" : "6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1002",
"image" : "https://n4.sdlcdn.com/imgs/i/z/i/HMTe-HM-9072-Metal-Analog-SDL494827480-1-db8fc.jpg",
"itemtotalprice" : "390",
"name" : "Metal Analog",
"price" : "390",
"productId" : "1002",
"quantity" : "1"
},
"6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1008" : {
"id" : "6OD9qfVX9LMN4CoWb6qmSJvXTlf2_1008",
"image" : "https://cdn4.ethoswatches.com/the-watch-guide/wp-content/uploads/2017/06/Top-10-Casio-G-Shock-Watches-Post-mobile-mast.jpg",
"itemtotalprice" : "80",
"name" : "G-Shock(casio)",
"price" : "80",
"productId" : "1008",
"quantity" : "1"
}
}
},
}

Users information not displaying in recyclerview

I'm working on this project where users are able to upload more than one character image along with other information. Such as the name of the character, what the character will do, the color of the character and its height. Now everything saves successfully in the database. However, when I want to display all of the character's information on the user's profile page, using a recyclerView, the saved information in the database will not display on the user's profile page. Below is my code. Thanks in advance
//Users profile page
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(getApplicationContext(), mUploads);
recyclerView = findViewById(R.id.recyclerView);
//recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if (firebaseAuth != null) {
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
//upload = findViewById(R.id.button_upload);
//button2 = findViewById(R.id.submit);
//imageView = findViewById(R.id.view_image);
//upload.setOnClickListener(this);
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = (String) postsnapshot.child("mImageUrl").getValue();
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
//Model Upload.class
public class Upload {
private String mImageUrl;
public Upload(){
//Empty constructor needed
}
public Upload (String imageUrl){
mImageUrl=imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
}
// Image adapter class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{
private Context mContext;
private List<String> mUploads;
public ImageAdapter(Context context, List<String> uploads){
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new ImageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
String uploadCurrent=mUploads.get(position);
Picasso.get().load(uploadCurrent).fit().centerCrop().into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.imageview);
}
}
}
Change this:
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = (String) postsnapshot.child("mImageUrl").getValue();
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
into this:
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
String imageUrl = postsnapshot.child("mImageUrl").getValue(String.class);
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
If you want to read inside the children of children, you need to do double loop like this.
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : postsnapshot.getChildren()) {
String imageUrl = snapshot.child("mImageUrl").getValue(String.class);
mUploads.add(imageUrl);
//mUploads = new ArrayList<>();
}
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
Edited:
If you want to pass all of them, you need to change a bit of your model class
public class Upload {
private String mImageUrl;
private String Character_Name;
private String What_Character_Does;
private String color;
private String height;
public Upload() {
//Empty constructor needed
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public String getCharacter_Name() {
return Character_Name;
}
public void setCharacter_Name(String character_Name) {
Character_Name = character_Name;
}
public String getWhat_Character_Does() {
return What_Character_Does;
}
public void setWhat_Character_Does(String what_Character_Does) {
What_Character_Does = what_Character_Does;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}

Recyclerview adding multiple items when only one was added

Firstly, I've looked into the existing questions that discuss similar issues as mine. Primarily this answer is the closet to the issue I'm having --> Link. I didn't see any solutions that fit my issue.
I've attached below the code for both my HomeFragment & HomeListAdapter. I've done some research as some say I shouldn't do the firebase database calls within the bindviewholder, but Firebase quick start database example is what I am following so if any firebase android engineers might give me some direction that would be great.
When I click add on my Edit Recipe Fragment. After the upload has completed it goes to the home fragment. The confusion I have is every other adapter I have in the app has the correct behavior. It only adds one recipe (only one is ever added at a time is the expected behavior).
HomeFragment
package com.irondigitalmedia.keep;
import java.util.ArrayList;
public class HomeFragment extends BaseFragment {
private static final String TAG = HomeFragment.class.getSimpleName();
private ArrayList<Recipe> mRecipeList;
private ArrayList<String> mRecipeIds;
private RecyclerView HomeRecyclerView;
private HomeListAdapter adapter;
private LinearLayoutManager LLM;
private Context mContext;
private FirebaseDatabase database;
private DatabaseReference myRef;
private Recipe mRecipe;
private User mUser;
private int likeCounter = 0;
private MainActivity mainActivity;
private BaseActivity baseActivity;
private Toolbar toolbar;
private ProgressBar progressBar;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
mContext = view.getContext();
mRecipeList = new ArrayList<>();
mRecipeIds = new ArrayList<>();
HomeRecyclerView = view.findViewById(R.id.frag_search_rv);
HomeRecyclerView.addItemDecoration(new SpacesItemDecoration(8));
LLM = new LinearLayoutManager(getContext());
HomeRecyclerView.setLayoutManager(LLM);
adapter = new HomeListAdapter(mContext, mRecipeList, mUser);
HomeRecyclerView.setAdapter(adapter);
mainActivity = (MainActivity) view.getContext();
mainActivity.mMainNav.setSelectedItemId(R.id.nav_home);
toolbar = mainActivity.findViewById(R.id.main_toolbar);
toolbar.setTitle("Home");
mainActivity.setSupportActionBar(toolbar);
if(savedInstanceState != null){
Log.e(TAG, "onCreateView: savedInstanceState is null");
}else{
LoadRecipes();
}
return view;
}
private void LoadRecipes() {
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
myRef.child(Constants.DATABASE_ROOT_FOLLOWING).child(getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String key = dataSnapshot.getKey();
Log.i(TAG, "onChildAdded: key is = " + key);
if(key!=null){
Log.i(TAG, "onChildAdded: key is not null ");
myRef.child(Constants.DATABASE_ROOT_USERS_RECIPES).child(key).limitToFirst(5).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
mRecipe = dataSnapshot.getValue(Recipe.class);
// [START_EXCLUDE]
// Update RecyclerView
mRecipeIds.add(dataSnapshot.getKey());
mRecipeList.add(mRecipe);
adapter.notifyItemInserted(mRecipeList.size() - 1);
// [END_EXCLUDE]
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
mRecipe = dataSnapshot.getValue(Recipe.class);
String recipeKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mRecipeIds.indexOf(recipeKey);
if (commentIndex > -1) {
// Replace with the new data
mRecipeList.set(commentIndex, mRecipe);
// Update the RecyclerView
adapter.notifyItemChanged(commentIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + recipeKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String recipeKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int commentIndex = mRecipeIds.indexOf(recipeKey);
if (commentIndex > -1) {
// Remove data from the list
mRecipeIds.remove(commentIndex);
mRecipeList.remove(commentIndex);
// Update the RecyclerView
adapter.notifyItemRemoved(commentIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + recipeKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
mRecipe = dataSnapshot.getValue(Recipe.class);
String recipeKey = dataSnapshot.getKey();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "recipes:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load recipes.",
Toast.LENGTH_SHORT).show();
}
});
}else{
Log.e(TAG, "onChildAdded: Key is null");
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(Constants.SAVED_STATE_HOME,mRecipeList);
}
#Override
public void onStart() {
super.onStart();
getActivity().setTitle("Home");
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
HomeListAdapter
package com.irondigitalmedia.keep.Adapters;
public class HomeListAdapter extends RecyclerView.Adapter<HomeListAdapter.ViewHolder> {
private static final String TAG = HomeListAdapter.class.getSimpleName();
private DatabaseReference mDatabase;
private Context context;
private List<Recipe> mRecipesList;
private MainActivity mainActivity;
private User user;
private int likeCounter = 0;
public HomeListAdapter(Context context, List<Recipe> mRecipesList, User user) {
this.context = context;
this.mRecipesList = mRecipesList;
this.user = user;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_recipes_recipe_item, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mainActivity = (MainActivity) view.getContext();
return new HomeListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Recipe recipe = mRecipesList.get(position);
SetUserData(holder, position);
holder.tv_recipe_title.setText(mRecipesList.get(position).getTitle());
holder.tv_recipe_prepTime.setText(mRecipesList.get(position).getPrepTime());
Glide.with(context).load(mRecipesList.get(position).getUrl())
.placeholder(R.drawable.ic_loading).thumbnail(0.05f).fitCenter()
.transition(DrawableTransitionOptions.withCrossFade()).centerCrop()
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.into(holder.recipe_thumbnail);
Log.i(TAG, "onBindViewHolder: Database Reference = " +
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES));
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
likeCounter = (int) dataSnapshot.getChildrenCount();
Log.i(TAG, "onDataChange: ChildrenCount = " + recipe.getTitle() + " " + likeCounter);
holder.tv_like_counter.setText(Integer.toString(likeCounter));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(getUid())){
holder.like.setLiked(true);
Log.i(TAG, "onDataChange: LIKED RECIPE...");
}else{
Log.i(TAG, "onDataChange: RECIPE IS NOT LIKED...");
holder.like.setLiked(false);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE)){
holder.tv_like_counter.setText(String.valueOf(dataSnapshot.child(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE).getValue()));
}else{
// likes do not exist
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.like.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Log.i(TAG, "liked: LIKED");
// Add like
holder.like.setLiked(true);
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).setValue("true");
}
#Override
public void unLiked(LikeButton likeButton) {
Log.i(TAG, "unLiked: UNLIKED");
// remove Like
holder.like.setLiked(false);
mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).removeValue();
}
});
}
private void SetUserData(ViewHolder holder, int position) {
mDatabase.child(Constants.DATABASE_ROOT_USERS).child(mRecipesList.get(position).getCreatorId())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
holder.tv_user_username.setText(user.getUsername());
Glide.with(context).load(user.getUrl()).centerCrop().placeholder(R.drawable.ic_loading).into(holder.userPhoto);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mRecipesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tv_recipe_title, tv_recipe_prepTime, tv_user_username, tv_like_counter;
public ImageView recipe_thumbnail;
public LikeButton like;
public CircleImageView userPhoto;
public LinearLayout user_ll;
public FirebaseAuth mAuth;
public FirebaseDatabase mDatabase;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mainActivity = (MainActivity) itemView.getContext();
mDatabase = FirebaseDatabase.getInstance();
tv_recipe_title = itemView.findViewById(R.id.recipe_item_title);
tv_recipe_prepTime = itemView.findViewById(R.id.recipe_item_time);
recipe_thumbnail = itemView.findViewById(R.id.recipe_item_photo);
like = itemView.findViewById(R.id.recipe_item_image_like);
tv_like_counter = itemView.findViewById(R.id.recipe_item_like_counter);
userPhoto = itemView.findViewById(R.id.recipe_item_user_photo);
tv_user_username = itemView.findViewById(R.id.recipe_item_user_username);
user_ll = itemView.findViewById(R.id.recipe_item_user_linearLayout);
user_ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment pf = new ProfileFragment();
if(pf.isAdded()){
return;
}else{
Bundle bundle = new Bundle();
bundle.putString(Constants.EXTRA_USER_UID,mRecipesList.get(getAdapterPosition()).getCreatorId());
Log.i(TAG, "onClick: Fragment Interaction recipe Creator Id = " + mRecipesList.get(getAdapterPosition()).getCreatorId());
FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
pf.setArguments(bundle);
ft.replace(R.id.main_frame, pf, Constants.FRAGMENT_TAG_PROFILE);
ft.addToBackStack(Constants.FRAGMENT_TAG_PROFILE);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
});
itemView.setOnClickListener(v -> {
RecipeDetailsFragment rd = new RecipeDetailsFragment();
if(rd.isAdded()){
return;
}else{
Bundle bundle = new Bundle();
bundle.putString(Constants.EXTRA_RECIPE_KEY,mRecipesList.get(getAdapterPosition()).getUid());
bundle.putString(Constants.EXTRA_RECIPE_CREATOR_ID, mRecipesList.get(getAdapterPosition()).getCreatorId());
Log.i(TAG, "onClick: Fragment Interaction recipe Key is = " + mRecipesList.get(getAdapterPosition()).getUid());
FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
rd.setArguments(bundle);
ft.replace(R.id.main_frame, rd, Constants.FRAGMENT_TAG_RECIPE_DETAILS);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
EditRecipeFragment
package com.irondigitalmedia.keep.Adapters;
public class EditIngredientAdapter extends RecyclerView.Adapter<EditIngredientAdapter.IngredientViewHolder> {
private static final String TAG = EditIngredientAdapter.class.getSimpleName();
private String dataSnapShotKey;
private Context mContext;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
public List<String> mIngredientIds = new ArrayList<>();
public List<Ingredient> mIngredients = new ArrayList<>();
public EditIngredientAdapter(final Context mContext, DatabaseReference ref) {
this.mContext = mContext;
this.mDatabaseReference = ref;
// Create child event listener
// [START child_event_listener_recycler]
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
dataSnapShotKey = dataSnapshot.getKey();
// A new comment has been added, add it to the displayed list
Ingredient ingredient = dataSnapshot.getValue(Ingredient.class);
// [START_EXCLUDE]
// Update RecyclerView
mIngredientIds.add(dataSnapshot.getKey());
mIngredients.add(ingredient);
notifyItemInserted(mIngredients.size() - 1);
// [END_EXCLUDE]
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Ingredient newIngredient = dataSnapshot.getValue(Ingredient.class);
String ingredientKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int ingredientIndex = mIngredientIds.indexOf(ingredientKey);
if (ingredientIndex > -1) {
// Replace with the new data
mIngredients.set(ingredientIndex, newIngredient);
// Update the RecyclerView
notifyItemChanged(ingredientIndex);
} else {
Log.w(TAG, "onChildChanged:unknown_child:" + ingredientKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String ingredientKey = dataSnapshot.getKey();
// [START_EXCLUDE]
int ingredientIndex = mIngredientIds.indexOf(ingredientKey);
if (ingredientIndex > -1) {
// Remove data from the list
mIngredientIds.remove(ingredientIndex);
mIngredients.remove(ingredientIndex);
// Update the RecyclerView
notifyItemRemoved(ingredientIndex);
} else {
Log.w(TAG, "onChildRemoved:unknown_child:" + ingredientKey);
}
// [END_EXCLUDE]
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Ingredient movedIngredient = dataSnapshot.getValue(Ingredient.class);
String ingredientKey = dataSnapshot.getKey();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load comments.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(childEventListener);
// [END child_event_listener_recycler]
// Store reference to listener so it can be removed on app stop
mChildEventListener = childEventListener;
}
#NonNull
#Override
public IngredientViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_item_recipe_ingredient, parent, false);
return new IngredientViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull IngredientViewHolder holder, int position) {
Ingredient ingredient = mIngredients.get(position);
holder.ingred.setText(ingredient.ingredient);
}
#Override
public int getItemCount() {
return mIngredients.size();
}
public class IngredientViewHolder extends RecyclerView.ViewHolder {
public TextView ingred;
public IngredientViewHolder(View itemView) {
super(itemView);
ingred = itemView.findViewById(R.id.recipe_ingredients_tv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Ingredient: " + mIngredients.get(getAdapterPosition()).ingredient, Toast.LENGTH_SHORT).show();
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "Long Clicked " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
public void RemoveIngredient(DatabaseReference reference){
reference.removeValue();
}
public void cleanupListener() {
if (mChildEventListener != null) {
mDatabaseReference.removeEventListener(mChildEventListener);
}
}
}
Screenshots:
Go To Search and back to home
Back to home
Attempted solution from Majuran (thank you), but it didn't work. Same result. When adding the list.clear() method to both lists.
In my understanding, One thing is added again in your view. when you come back to the same fragment right? (I got the same issue in my last project)
The problem is in HomeFragment. Same values are adding again in your these lists.
mRecipeList = new ArrayList<>();
mRecipeIds = new ArrayList<>();
so clear it, before adding the listener
myRef = database.getReference();
mRecipeList.clear();
mRecipeIds.clear();
myRef.child(Constants.DATABASE_ROOT_FOLLOWING).child(getUid()).add...
Hope its helpful, Happy coding!!!
I was able to resolve this by putting the database call inside the constructor of the adapter. This is the same practice that is within the example that the firebase team put inside their database example app.

Displaying messages from firebase database

I'm creating a social messaging app.
the ideal on how the app function is where the messages are saved to the firebase database and then displayed on the RecyclerView.. the messages are saved to the database but not displayed on the RecyclerView.
please help...
thank you
message adopter class.
public class MessagesAdopter extends RecyclerView.Adapter {
public MessagesAdopter(List<Messages> messagesList) {
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
public class MessageAdopter extends RecyclerView.Adapter<MessageAdopter.MessageViewHolder> {
private List<Messages> usersmessengeslist;
private FirebaseAuth mAuth;
private DatabaseReference userdatabaseref;
public MessageAdopter (List<Messages> usersmessengeslist){
this.usersmessengeslist = usersmessengeslist;
}
public class MessageViewHolder extends RecyclerView.ViewHolder {
private TextView sender_typed_message,reciever_typed_message;
CircleImageView reciever_image_view;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
sender_typed_message = itemView.findViewById(R.id.sender_typed_message);
reciever_typed_message = itemView.findViewById(R.id.reciever_typed_message);
reciever_image_view = itemView.findViewById(R.id.reciver_profile_image);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_message_layout,parent ,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, int position) {
String messagesenderid = mAuth.getCurrentUser().getUid();
Messages messages = usersmessengeslist.get(position);
String fromUserID = messages.getFrom();
String frommessagetype = messages.getType();
userdatabaseref = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
userdatabaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String image = dataSnapshot.child("profileimage").getValue(String.class);
Picasso.get().load(image).placeholder(R.drawable.profile).into(holder.reciever_image_view);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (frommessagetype.equals("text")){
holder.reciever_image_view.setVisibility(View.INVISIBLE);
holder.reciever_typed_message.setVisibility(View.INVISIBLE);
if (fromUserID.equals(messagesenderid)){
holder.sender_typed_message.setBackgroundResource(R.drawable.sender_message_background);
holder.sender_typed_message.setTextColor(Color.WHITE);
holder.sender_typed_message.setGravity(Gravity.LEFT);
holder.sender_typed_message.setText(messages.getMessage());
}
else
{
holder.sender_typed_message.setVisibility(View.INVISIBLE);
holder.reciever_typed_message.setVisibility(View.VISIBLE);
holder.reciever_image_view.setVisibility(View.VISIBLE);
holder.reciever_typed_message.setBackgroundResource(R.drawable.reciever_message_background);
holder.reciever_typed_message.setTextColor(Color.WHITE);
holder.reciever_typed_message.setGravity(Gravity.LEFT);
holder.reciever_typed_message.setText(messages.getMessage());
}
}
}
#Override
public int getItemCount() {
return usersmessengeslist.size();
}
}
}
chat activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
messagesenderuserIdD = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
recievereruserid = getIntent().getExtras().get("visit_user_id").toString();
recieverrusername = getIntent().getExtras().get("userName").toString();
iniitializefeildz();
displayrecieveruserinformtion();
sendmessagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendusermessage();
}
});
fetchmessage();
}
private void fetchmessage() {
RootRef.child("Messages").child(messagesenderuserIdD).child(recievereruserid)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
mMessagesList.add(messages);
MessagesAdopter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendusermessage() {
String messagetext = user_inout_message.getText().toString();
if (TextUtils.isEmpty(messagetext)){
Toast.makeText(chatActivity.this,"please type a message",Toast.LENGTH_SHORT).show();
}
else {
String message_sender_ref = "Messages/" + messagesenderuserIdD + "/" + recievereruserid;
String message_reciever_ref = "Messages/" + recievereruserid + "/" + messagesenderuserIdD;
DatabaseReference user_message_key = RootRef.child("Message").child(messagesenderuserIdD).child(recievereruserid).push();
String message_push_id =user_message_key.getKey();
Calendar callforddate = Calendar.getInstance();
SimpleDateFormat currentdate =new SimpleDateFormat("dd-MMMM-yyyy");
savecurrentdate= currentdate.format(callforddate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
savecurrenttime = currentTime.format(callforddate.getTime());
Map messageTextbody = new HashMap();
messageTextbody.put("Message", messagetext);
messageTextbody.put("time", savecurrenttime);
messageTextbody.put("date", savecurrentdate);
messageTextbody.put("type", "text");
messageTextbody.put("from", messagesenderuserIdD);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/"+ message_push_id,messageTextbody);
messageBodyDetails.put(message_reciever_ref + "/"+ message_push_id,messageTextbody);
RootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(chatActivity.this,"message sent successfully",Toast.LENGTH_SHORT).show();
user_inout_message.setText("");
}
else {
String message = task.getException().getMessage();
Toast.makeText(chatActivity.this,"Error" + message,Toast.LENGTH_SHORT).show();
user_inout_message.setText("");
}
}
});
}
}
private void displayrecieveruserinformtion() {
chat_username.setText(recieverrusername);
RootRef.child("Users").child(recievereruserid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final String profileimage = dataSnapshot.child("profileimage").getValue(String.class);
Picasso.get().load(profileimage).placeholder(R.drawable.profile).into(chat_circular_imageview);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void iniitializefeildz() {
mToolbar = findViewById(R.id.action_cjat_bar);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_appbar,null);
actionBar.setCustomView(action_bar_view);
chat_username = findViewById(R.id.user_chat_displayname);
chat_circular_imageview = findViewById(R.id.user_chat_displayimage);
user_inout_message= findViewById(R.id.chat_write_message_here);
sendmessagebutton = findViewById(R.id.send_chat_message);
sendimagemessage = findViewById(R.id.chat_chooseimage);
MessagesAdopter = new MessagesAdopter(mMessagesList);
messagesview = findViewById(R.id.messageview_list);
linearlayoutmanager = new LinearLayoutManager(this);
messagesview.setHasFixedSize(true);
messagesview.setLayoutManager(linearlayoutmanager);
messagesview.setAdapter(MessagesAdopter);
}
}
hi i am fatching my massages from firebase database with this, try this it will help you :-
private void readMessage(final String myId, final String userId) {
mChat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference(chatTableName);
try {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
Chat chat = null;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
chat = snapshot.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userId) ||
chat.getReceiver().equals(userId) && chat.getSender().equals(myId)) {
mChat.add(chat);
}
adapter = new MessageAdapter(UserMessageActivity.this, mChat);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (Exception e) {
Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

I'm Having some trouble obtaining a new message - Android

I'm having some trouble obtaining a new message.
So my algorithm works like this. I receive the last message from the chat(in Firebase), and if the last message UserId is not equal to mine than it sets a Boolean(newMessage) to true to make it a new message.
When i click on it, the variable sets to false. However when i re-run the application the Boolean does not stay the same, it just resets itself.
What should i do, to fix this?
Here is the code :
MessengerMessagesFragment.java
public class MessengerMessagesFragment extends Fragment{
private static final String TAG = "MessengerMessagesFragme";
private List<User> mUserList;
private static final int SIGN_IN_REQUEST_CODE = 111;
private ListView mListView;
private ArrayList<String> mUsersInM;
private MessagesListAdapter mAdapter;
User user;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_messenger_messages, container, false);
mListView = (ListView) view.findViewById(R.id.lvMessages);
mUserList = new ArrayList<>();
mUsersInM = new ArrayList<>();
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
getUsersInM();
}
return view;
}
private void updateUserslist(){
Log.d(TAG, "updateUsersList: updating users list");
mAdapter = new MessagesListAdapter(getActivity(), R.layout.layout_message_listitem, mUserList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "onItemClick: selected user: " + mUserList.get(position).toString());
mAdapter.setNewMessage(false);
Log.e(TAG, "onItemClick: Set new message bool " + mAdapter.isNewMessage());
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(getString(R.string.intent_user), mUserList.get(position));
startActivity(intent);
}
});
}
private void getMessages(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
for(int i = 0; i < mUsersInM.size(); i++){
final int count = i;
Query query = reference
.child(getString(R.string.dbname_users))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mUsersInM.get(i));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
mUserList.add(singleSnapshot.getValue(User.class));
}
if(count >= mUsersInM.size() - 1){
updateUserslist();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void getUsersInM(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
mUsersInM.add(singleSnapshot.getKey().toString());
Log.d(TAG, "onDataChange: Message user id: " + mUsersInM.toString() );
}
getMessages();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
MessagesListAdapter.java
public class MessagesListAdapter extends ArrayAdapter<User> {
private static final String TAG = "MessageListAdapter";
private LayoutInflater mInflater;
private List<User> mUsers = null;
private int layoutResource;
private Context mContext;
private int messagesCount = 0;
DatabaseReference myRef;
public boolean newMessage;
public boolean isNewMessage() {
return newMessage;
}
public void setNewMessage(boolean newMessage) {
this.newMessage = newMessage;
}
//private int msgC;
private String userID;
public MessagesListAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<User> objects) {
super(context, resource, objects);
mContext = context;
myRef = FirebaseDatabase.getInstance().getReference();
//getMessagesCount();
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutResource = resource;
this.mUsers = objects;
}
private static class ViewHolder{
TextView username, message, timeStamp;
ImageView profileImage, statusOnline, statusOffline;
RelativeLayout messageBackground;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.username = (TextView) convertView.findViewById(R.id.f_username);
holder.message = (TextView) convertView.findViewById(R.id.m_message);
holder.profileImage = (ImageView) convertView.findViewById(R.id.f_profile_image);
holder.timeStamp = (TextView) convertView.findViewById(R.id.m_timestamp);
holder.statusOnline = (ImageView) convertView.findViewById(R.id.iv_Online);
holder.statusOffline = (ImageView) convertView.findViewById(R.id.iv_Offline);
holder.messageBackground = (RelativeLayout) convertView.findViewById(R.id.RelLayoutMessage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.username.setText(getItem(position).getUsername());
//holder.email.setText(getItem(position).getEmail());
//DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = myRef.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot: dataSnapshot.getChildren()){
//Log.d(TAG, "onDataChange: found user: " + singleSnapshot.getValue(UserAccountSettings.class).toString());
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profileImage);
userID = singleSnapshot.getValue(User.class).getUser_id();
boolean is_Online = singleSnapshot.getValue(User.class).isOnline();
if(is_Online == true){
holder.statusOnline.setVisibility(View.VISIBLE);
holder.statusOffline.setVisibility(View.GONE);
}else if(is_Online == false){
holder.statusOnline.setVisibility(View.GONE);
holder.statusOffline.setVisibility(View.VISIBLE);
}
}
setMessageItemSettings(holder, userID);
getNewMessage(holder, userID);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return convertView;
}
private void getNewMessage(final ViewHolder holder, final String user_id){
Query lastMessageQuery = myRef.child(mContext.getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(user_id).orderByKey().limitToLast(1);
lastMessageQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String messageUid = data.child(mContext.getString(R.string.field_messageUserId)).getValue().toString();
Log.e(TAG, "onDataChange: *************** MESSAGE FROM USER *************** : " + messageUid + " ====== " + newMessage);
if(messageUid.equals(user_id)){
newMessage = true;
Log.e(TAG, "onDataChange: *************** NEW MESSAGE FROM USER *************** : " + messageUid + " ====== " + newMessage);
if(newMessage){
holder.messageBackground.setBackgroundColor(Color.parseColor("#b7b7b7"));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setMessageItemSettings(final ViewHolder holder, final String user_id){
Log.e(TAG, "getView: USER ID************************************" + userID);
Log.e(TAG, "getView: USER ID************************************" + messagesCount);
//msgC = messagesCount;
//DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference();
Query lastMessageQuery = myRef.child(mContext.getString(R.string.dbname_messages))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(user_id).orderByKey().limitToLast(1);
lastMessageQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: THINGS--------------+++ ---" + dataSnapshot.toString());
Log.e(TAG, "getView: USER ID************************************" + userID);
Log.e(TAG, "getView: USER ID************************************" + messagesCount);
//String lastItem = dataSnapshot.getValue().toString();
for (DataSnapshot data : dataSnapshot.getChildren()) {
try{
String mMessage = data.child(mContext.getString(R.string.field_messageText)).getValue().toString();
holder.message.setText(mMessage);
String mTime = data.child(mContext.getString(R.string.field_messageTime)).getValue().toString();
holder.timeStamp.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", Long.valueOf(mTime)));
}catch(NullPointerException e){
Log.e(TAG, "onDataChange: *************** GETTING MESSAGES FROM USER ARE NULL *************** : " + e.getMessage());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
//Log.d(TAG, "getView: USER ID****************" + userID);
}
Firebase Message Structure :
Are you saving the newMessage = true; statement in somewhere?
i have fixed it buy putting a new_message variable in user_id node 2(WI8yTLA...) on firebase and that solved my problem.

Categories

Resources