Users information not displaying in recyclerview - android

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

Related

Dynamic Expandable Recyclerview List Failing

I'm new to Android and I know this might be a piece of cake but I'm struggling.
I was trying to create a dynamic expandable recycler view using firebase realtime database but the data is not displaying properly.
I'm passing a string from one activity to another and comparing the string to the database field and then displaying it's child components but I don't know where I'm failing.
I want to display the Parent and child field by comparing the name field with the value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_detail);
//string value from another activity
String value = getIntent().getExtras().getString("name");
recycler_view = (RecyclerView) findViewById(R.id.recycler_expand);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentReference = database.getReference().child("Tutors");
//comparing
parentReference.equalTo(value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ParentList> Parent = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String ParentKey = snapshot.getKey().toString();
snapshot.child("title").getValue();
DatabaseReference childReference =
FirebaseDatabase.getInstance().getReference().child(ParentKey);
childReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChildList> Child = new ArrayList<>();
for (DataSnapshot snapshot1:dataSnapshot.getChildren())
{
final String ChildValue = snapshot1.getValue().toString();
snapshot1.child("title").getValue();
Child.add(new ChildList(ChildValue));
}
Parent.add(new ParentList(ParentKey, Child));
DocExpandableRecyclerAdapter adapter = new DocExpandableRecyclerAdapter(Parent);
recycler_view.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database Structure
ChildList.java
public class ChildList implements Parcelable {
private String title;
public ChildList(String title) {
this.title = title;
}
protected ChildList(Parcel in) {
title = in.readString();
}
public static final Creator<ChildList> CREATOR = new Creator<ChildList>() {
#Override
public ChildList createFromParcel(Parcel in) {
return new ChildList(in);
}
#Override
public ChildList[] newArray(int size) {
return new ChildList[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String Title) {
this.title = Title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
}
Please anyone help me with this :(
Don't use equalTo().
Try this:
DatabaseReference parentReference = database.getReference().child("Tutors");
parentReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String NameKey = snapshot.getKey().toString();
if(value.equals(NameKey)){
//DO WHATEVER YOU WANT
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to retrieve data from Firebase and show the childrens one by one in recyclerView

I have 2 clases.One is Groups and the other one is GroupListAdapter. With the method RetrieveGroups i try to get the children of GroupName and show them one by one in recyclerView.
The value of string "retrieveGroupsName" its like in database.
TX!
i
public void RetrieveGroups(){
GroupReF.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (final DataSnapshot ds :dataSnapshot.getChildren()){
String uid = ds.getKey();
DatabaseReference groupRef = GroupReF.child(uid).child("GroupName");
groupRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String retrieveGroupsName = dataSnapshot.getValue().toString();
Log.i(TAG,"value --------+++++++++++++" + retrieveGroupsName);
Groups groups = new Groups(retrieveGroupsName);
groupsList.clear();
groupsList.add(groups);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public class GroupsListAdapter extends RecyclerView.Adapter<GroupsListAdapter.GroupListViewHolder> {
private final String TAG = "Groups adapter Activity";
ArrayList<Groups> groupsList;
public GroupsListAdapter(ArrayList<Groups> groupsList) {
this.groupsList = groupsList;
}
#NonNull
#Override
public GroupsListAdapter.GroupListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.display_group_layout,parent,false);
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
GroupListViewHolder groupListViewHolder = new GroupListViewHolder(view);
return groupListViewHolder;
}
#Override
public void onBindViewHolder(#NonNull GroupListViewHolder holder, int position) {
holder.groupName.setText(groupsList.get(position).getGroupName());
}
#Override
public int getItemCount() {
return (groupsList == null) ? 0 : groupsList.size();
}
public class GroupListViewHolder extends RecyclerView.ViewHolder{
public TextView groupName;
public GroupListViewHolder(#NonNull View itemView) {
super(itemView);
groupName = itemView.findViewById(R.id.display_group_name);
}
}
}
public class Groups {
public String groupName;
public Groups(String groupName) {
this.groupName = groupName;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
You should chang your codes like this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
groupsList.clear();
for(DataSnapshot data : dataSnapshot.getChildren()){
String retrieveGroupsName = data.getValue(String.class);
Log.i(TAG,"value --------+++++++++++++" + retrieveGroupsName);
Groups groups = new Groups(retrieveGroupsName);
groupsList.add(groups);
}
yourAdapter.notifyDataSetChanged();
}

How to show multiple random childs from Firebase Realtime Database

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

How can i fill the recylerview with firebase realtime database data?

I tried so many solutions about this, but none of this resolve my problem. I can not reach the database using recyclerview. I have firebase realtime database data like this;
Tag
--- Main Category
----- keyID
------ main-Category, sub-category
Tags class
public class Tags {
private String id;
private String mainTags;
private String subTags;
public Tags() {}
public Tags(String id, String mainTags, String subTags) {
this.id = id;
this.mainTags = mainTags;
this.subTags = subTags;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMainTags() {
return mainTags;
}
public void setMainTags(String mainTags) {
this.mainTags = mainTags;
}
public String getSubTags() {
return subTags;
}
public void setSubTags(String subTags) {
this.subTags = subTags;
}
}
and this is TagAdapter
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.ItemViewHolder> {
private List<Tags> mTagList;
private Context mContext;
public TagAdapter(List<Tags> mTagList, Context mContext) {
this.mTagList = mTagList;
this.mContext = mContext;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item_tags, parent,false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Tags tags = mTagList.get(position);
holder.tvTags.setText(tags.getSubTags());
holder.tvMainTags.setText(tags.getMainTags());
}
#Override
public int getItemCount() {
return mTagList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView tvMainTags, tvTags;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
tvMainTags = itemView.findViewById(R.id.tvMainTag);
tvTags = itemView.findViewById(R.id.tvTags);
}
}
}
TagsFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tags, container, false);
rvTags = view.findViewById(R.id.rvTags);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvTags.setLayoutManager(linearLayoutManager);
rvTags.hasFixedSize();
tagAdapter = new TagAdapter(tagsList, getContext());
rvTags.setAdapter(tagAdapter);
return view;
}
private void getTagView(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference dbRefTags = firebaseDatabase.getReference().child("Tag");
dbRefTags.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
if (ds.exists()) {
try {
Tags tags = ds.getValue(Tags.class);
tagsList.add(tags);
}catch (Exception e){
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getContext(), "Bir hata oluştu", Toast.LENGTH_SHORT).show();
}
}
tagAdapter.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) {
}
});
}
There is no error show up when running but i couldn't be able to retrieve data. And i tried firebaseRecyclerView.Adapter also and in the last dependency, i couldn't make it work. I don't know what is wrong in here. how can i solve this?
Get The data with child name ds.child("SubTag").getValue()
dbRefTags.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot parentDS : dataSnapshot.getChildren()) {
Log.d("Tag:", String.valueOf(parentDS.getKey()));
for (DataSnapshot ds : parentDS.getChildren()) {
Tags tags = new Tags();
tags.setMainTag(parentDS.getKey());
tags.setSubTag(ds.child("SubTag").getValue().toString());
Log.d("Tag: -> SubTag)", tags.getSubTag());
tagsList.add(tags);
}
}
tagAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});

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

Categories

Resources