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.
Related
I am currently using Value Event Listener in my Code to show messages and it does not shows any error but my only problem is when whenever i add a new send or receive a new message my whole list gets updated all the previous messages are called and it uses a lot of memory currently i am taking care of it my clearing recyclerview every time the value event listener is called but now i want to add Child Event Listener in place of value event listener to save memory but whenever i add child event listener my messages are shown multiple times in recyclerview but after i restart the activity there is only one message in recyclerview.
MyCode
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView user_name;
FirebaseFirestore fstore;
FirebaseAuth fAuth;
FirebaseUser fuser;
DatabaseReference reference;
Toolbar toolbar;
ImageButton imageButton;
EditText textsend;
String userID;
MessageAdapter messageAdapter;
List<Chat> mChat;
RecyclerView recyclerView;
String TAG = "MyTag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
fAuth=FirebaseAuth.getInstance();
fstore=FirebaseFirestore.getInstance();
userID = fAuth.getCurrentUser().getUid();
profile_image=findViewById(R.id.profile_image);
user_name=findViewById(R.id.username);
imageButton=findViewById(R.id.btn_send);
textsend=findViewById(R.id.text_send);
recyclerView=findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager= new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
toolbar=findViewById(R.id.myToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Intent intent=getIntent();
fuser=FirebaseAuth.getInstance().getCurrentUser();
String userid=intent.getStringExtra("userid");
String username= intent.getStringExtra("UserName");
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
user_name.setText(user.getFirst());
if (user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
//and this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
readMessages(fuser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=textsend.getText().toString();
textsend.setText("");
if (!msg.equals("")){
sendMessage(fuser.getUid(),userid,msg);
}
else {
Toast.makeText(MessageActivity.this,"Empty messages cant be send",Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendMessage(String sender, final String receiver, String message) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
String key = reference.push().getKey();
reference.child(key).setValue(hashMap);
}
private void readMessages(String myid,String userid,String imageurl){
mChat=new ArrayList<>();
reference=FirebaseDatabase.getInstance().getReference("Chats");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Chat chat= dataSnapshot.getValue(Chat.class);
assert chat!=null;
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid)||
chat.getReceiver().equals(userid)&&chat.getSender().equals(myid)){
chat.setMessageId(dataSnapshot.getKey());
mChat.add(chat);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Chat chat=dataSnapshot.getValue(Chat.class);
chat.setMessageId(dataSnapshot.getKey());
mChat.remove(chat);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren()) {
Chat 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);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
}
MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<Chat> mChat;
String imageurl;
FirebaseUser fuser;
public MessageAdapter(Context mContext, List<Chat> mChat,String imageurl) {
this.mContext = mContext;
this.mChat = mChat;
this.imageurl=imageurl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
}
else {
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat=mChat.get(position);
holder.show_message.setText(chat.getMessage());
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
holder.show_message.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
String message_id=chat.getMessageId();
Task<Void> task = Utils.removeUser(message_id);
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(mContext,"Message Deleted",Toast.LENGTH_SHORT).show();
}
});
return true;
}
});
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView show_message;
public ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message=itemView.findViewById(R.id.show_message);
profile_image=itemView.findViewById(R.id.profile_image);
}
}
#Override
public int getItemViewType(int position) {
fuser= FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return MSG_TYPE_RIGHT;
}
else {
return MSG_TYPE_LEFT;
}
}
}
Use below code. Remove ValueEventListener calls. You should add your logic inside onChildAdded
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Chat chat= dataSnapshot.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);
Log.d(TAG,"msg "+chat.getMessage());
}
messageAdapter=new MessageAdapter(MessageActivity.this,mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
messageAdapter.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) {
}
});
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)).limitToFirst(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);
I've tried everything and looked at these questions (one, two, three(vid tut)) for answers and tried them, but still to no avail am I able to set the childrencount that I can clearly see in the logs using an int into a textview.
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 ProgressBar progressBar;
private int likeCounter = 0;
public HomeListAdapter(Context context, List<Recipe> mRecipesList) {
this.context = context;
this.mRecipesList = mRecipesList;
}
#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();
progressBar = mainActivity.findViewById(R.id.main_progressBar);
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{
holder.tv_like_counter.setText("0");
}
}
#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);
Log.i(TAG, "CheckLikeStatus: " + recipe.title + " " + recipe.hasLiked);
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);
Log.i(TAG, "CheckLikeStatus: " + recipe.title + " " + recipe.hasLiked);
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();
}
}
So, after checking the logs, it is very clear that there is nothing wrong with the Firebase. But, there is something wrong with your view binding process with the adapter. The tutorials which you are following right now, is not going to help, since everything is okay on the firebase side.
The problem is, that when you are calling
holder.tv_like_counter.setText(Integer.toString(likeCounter)); ,
tv_like_counter is not even prepared yet.
It would be great if you can show how you are binding your views in the adapter. If not, you can also refer this link to solve your problem. At Least now you know in which direction you need to search ;)
I did a bit more of a different perspective look after checking the view bindings. I found that there was a contradiction. See below:
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
holder.tv_like_counter.setText("0");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I removed holder.tv_like_counter.setText("0");. It's supposed to only set it to 0 if the snapshot didn't have the child. I simply forgot the logic I had in place when I was troubleshooting.
Don't do fetching data from database operation inside the onBindViewHolder, It is a very bad practice and data calls will be created every time when the view comes to display.
And it won't be completed that's why you did not get the output. because before getting output it may be destroyed.
Do whole data related operations inside your Activity and pass the
data to Adapter.
See this
Happy coding !!!
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();
}
}
My database structure
I am trying to create an activity where I can display all the logs. Just timestamp and the log message. I have tried with firebaseUI and adapter but I can't get the data to show. Best I have done was to post same last log in all positions. This is what I have so far but no success. I am new to firebase and all I need is to display the logs in a list. It can be lisView or recyclerView. If anyone can help me with code or example. Thank you.
Database structure is | "logs" node / userId / logId / fields |
public class LogActivity extends AppCompatActivity {
private static final String TAG = "LogActivity";
private static final int ACTIVITY_NUM = 3;
//widgets
private Context mContext = LogActivity.this;
private RecyclerView mLogRecycleView;
private TextView timeStamp, log;
//firebase
private DatabaseReference mLogDatabase;
private FirebaseAuth mAuth;
//adapter
private FirebaseRecyclerAdapter adapter;
//vars
private String mCurrentUserID, logID;
List<AppLogs> logsList = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
Log.d(TAG, "onCreate: Started");
mCurrentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mLogRecycleView = findViewById(R.id.recyclerList);
mLogDatabase = FirebaseDatabase.getInstance().getReference().child("logs").child(mCurrentUserID);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mLogRecycleView.setHasFixedSize(true);
mLogRecycleView.setLayoutManager(linearLayoutManager);
firebaseListAdapter();
mLogRecycleView.setAdapter(adapter);
setupBottomNavigationView();
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
private void firebaseListAdapter() {
Log.d(TAG, "firebaseListAdapter: started");
Query logQuery = mLogDatabase.orderByChild("time");
FirebaseRecyclerOptions<AppLogs> options =
new FirebaseRecyclerOptions.Builder<AppLogs>()
.setQuery(logQuery, AppLogs.class).build();
adapter = new FirebaseRecyclerAdapter<AppLogs, LogViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
//final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singData : dataSnapshot.getChildren()) {
//AppLogs logs = dataSnapshot.getValue(AppLogs.class);
Log.d(TAG, "onChildAdded: log:==== " + singData.child("log").getValue());
//Log.d(TAG, "onChildAdded: log_ID:==== " + logs.getLog_id());
String log = singData.child("log").getValue().toString();
// String timeStamp = Long.toString(logs.getTime());
//
holder.setLog(log);
// holder.setTimeStamp(timeStamp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public LogViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: create users view holder: ");
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_log_list_view, parent, false);
return new LogViewHolder(view);
}
};
}
public static class LogViewHolder extends RecyclerView.ViewHolder {
View mView;
public LogViewHolder(View itemView) {
super(itemView);
this.mView = itemView;
}
public void setLog(String log) {
TextView tvLog = mView.findViewById(R.id.tvLog);
tvLog.setText(log);
}
public void setTimeStamp(String timeStamp) {
TextView tvTimeStamp = mView.findViewById(R.id.tvTimeStamp);
tvTimeStamp.setText(timeStamp);
}
}
/*
*BottomNavigationView Setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
and my log model class
package com.logistics.alucard.socialnetwork.Models;
public class AppLogs {
private String log, log_id;
private long time;
public AppLogs(String log, String log_id, long time) {
this.log = log;
this.log_id = log_id;
this.time = time;
}
public AppLogs() {
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
public String getLog_id() {
return log_id;
}
public void setLog_id(String log_id) {
this.log_id = log_id;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
I manage to figure it out! Thank you for your help. Still a bit confusing how to
build queries but I'll try to get better :)
This is my solution to the firebase retrieve data:
protected void onBindViewHolder(#NonNull final LogViewHolder holder, int position, #NonNull AppLogs model) {
Log.d(TAG, "onBindViewHolder: started");
//get the ID of the messages
final String logID = getRef(position).getKey();
//Log.d(TAG, "onBindViewHolder: logID : " + logID);
Query logQuery = mLogDatabase;
logQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//AppLogs appLogs = dataSnapshot.getValue(AppLogs.class);
//Log.d(TAG, "onDataChange: logs:---------" + dataSnapshot.child(logID).child("log").getValue());
String log = dataSnapshot.child(logID).child("log").getValue().toString();
String timeStamp = dataSnapshot.child(logID).child("time").getValue().toString();
Log.d(TAG, "onDataChange: logs:--------------" + log);
holder.setLog(log);
holder.setTimeStamp(timeStamp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});