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();
}
}
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'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;
}
}
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 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();
}
});
I'm building a chat application using firebase, i want to sort the chat list according to most recent message. The user you sent a message to last should appear at the top. Previous messages should come below, please help!
I've already tried orderbychild("time") it didn't work.
Chats Fragment
public class ChatsFragment extends Fragment {
private View PrivateChatView;
private RecyclerView chatsList;
private RecyclerView chatsLists;
private DatabaseReference ChatsRef,
UsersRef,
RootRef,
MsgRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String currentUserID;
private String theLastMessage;
public ChatsFragment() { // Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment
PrivateChatView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
mUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
MsgRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
RootRef = FirebaseDatabase.getInstance().getReference();
chatsList = (RecyclerView)PrivateChatView.findViewById(R.id.chats_list);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
chatsList.setLayoutManager(layoutManager);
chatsLists = (RecyclerView)PrivateChatView.findViewById(R.id.chats_lists);
chatsLists.setLayoutManager(new LinearLayoutManager(getContext()));
updateToken(FirebaseInstanceId.getInstance().getToken());
return PrivateChatView;
}
private void updateToken(String token) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
Token token1 = new Token(token);
reference.child(currentUserID).setValue(token1);
}
#Override public void onStart() {
super.onStart();
chats();
friends();
}
private void chats() {
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(MsgRef.getRef().orderByChild("date"), Friends.class).build();
FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
#Override protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull final Friends model) {
final String usersID = getRef(position).getKey();
final String[] retImage = {
"default_image"
};
final String list_user_id = getRef(position).getKey();
Query lastMessageQuery = MsgRef.child(list_user_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("time").getValue().toString();
String data1 = dataSnapshot.child("date").getValue().toString();
holder.userStatus.setText(data + " " + data1);
holder.userStatus.setTypeface(null, Typeface.NORMAL);
}
#Override public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override public void onCancelled(DatabaseError databaseError) {}
});
UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
chatIntent.putExtra("visit_user_id", usersID);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage);
startActivity(chatIntent);
}
});
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
#NonNull #Override public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
private void friends() {
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(ChatsRef, Friends.class).build();
FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
#Override protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull final Friends model) {
final String usersID = getRef(position).getKey();
final String[] retImage = {
"default_image"
};
final String list_user_id = getRef(position).getKey();
UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
chatIntent.putExtra("visit_user_id", usersID);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage);
startActivity(chatIntent);
}
});
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
#NonNull #Override public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsLists.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userStatus,
userName;
ImageView icon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userStatus = itemView.findViewById(R.id.user_status);
userName = itemView.findViewById(R.id.user_profile_name);
icon = itemView.findViewById(R.id.user_online_status);
}
}
}