Firebase
FirebaseRecyclerOptions<SQLiteHelper> options =
new FirebaseRecyclerOptions.Builder<SQLiteHelper>()
.setQuery(mFetchingMessages, SQLiteHelper.class)
.build();
final MainData mHelper = new MainData(this);
final Cursor csr = myDBHlpr.getAllQuestions3();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<SQLiteHelper, Chat.MessagesViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final Chat.MessagesViewHolder holder, final int position, #NonNull final SQLiteHelper model) {
final DatabaseReference mTimeReference = FirebaseDatabase.getInstance().getReference().child("Messages").child(MessageSenderId).child(MessageRecieverId);
Query messageQuery = mTimeReference.limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
SQLiteHelper message = dataSnapshot.getValue(SQLiteHelper.class);
}
#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) {
}
});
messages.add(message);
}
}
#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) {
}
});
#Override
public Chat.MessagesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_activity_chat, parent, false);
return new Chat.MessagesViewHolder(view);
}
};
messageList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
SQLite
while (csr.moveToNext()) {
String mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
String mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
long mTime = csr.getLong(csr.getColumnIndex(KEY_TIME));
String mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
String mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
String mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
messages.add(new SQLiteHelper(mSender, mMessage, mType, mSeen, mTimer, mTime));
mAdapter.notifyDataSetChanged();
When i have both only the firebase data is shown and when i remove or comment the firebase part of code the sqlite part of code is shown in recyclerview. Can someone suggest me to make the firebase code show below the sqlite code somehow please?
Related
I have an ImageView which acts as a like button and when a user clicks on it, it changes to a different ImageView which indicates that that comment was liked. The problem is that when I click on one, more than one gets selected. Let's say that there are 6 comments in the list and I "like" the 4th comment, other ones get "liked" also which shouldn't happen. The only one that should be getting "liked" is the one I click on. How can I fix this?
CommentAdapter
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Comment comment = mCommentList.get(position);
holder.comment.setText(comment.getComment());
commentLike(comment.getCommentid(), holder.commentLike);
commentDislike(comment.getCommentid(), holder.commentDislike);
holder.commentLike.setOnClickListener(v -> {
if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("dislike")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
} else if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("disliked")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
removeDislike(comment.getCommentid());
} else {
removeLike(comment.getPublisher(), comment.getCommentid());
}
});
holder.commentDislike.setOnClickListener(v -> {
if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("like")) {
dislikeComment(comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("liked")) {
dislikeComment(comment.getCommentid());
removeLike(comment.getPublisher(), comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else {
removeDislike(comment.getCommentid());
}
});
holder.itemView.setOnLongClickListener(v -> {
if (comment.getPublisher().equals(mFirebaseUser.getUid())) {
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle("Would you like to delete this comment?");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "No", (dialog, which) -> dialog.dismiss());
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", (dialog, which) -> {
deleteCommentNotification(mPostId, comment.getCommentid());
FirebaseDatabase.getInstance().getReference("Comments Liked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Comments Disliked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Responses").child(comment.getCommentid()).setValue(null);
Toast.makeText(mContext, "Your comment has been deleted.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
});
alertDialog.show();
}
return true;
});
static class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image_profile;
TextView username, comment, commentLikesNumber, commentDislikesNumber, commentResponseNumber, timestamp;
ImageView commentLike, commentDislike, iconComment;
ViewHolder(#NonNull View itemView) {
super(itemView);
commentLike = itemView.findViewById(R.id.icon_thumb_up_grey);
commentDislike = itemView.findViewById(R.id.icon_thumb_down_grey);
}
}
private void commentLike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Liked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_up_blue);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_up_grey);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void commentDislike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Disliked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_down_blue);
imageView.setTag("disliked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_down_grey);
imageView.setTag("dislike");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
CommentsActivity
private void readComments() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(mPostId);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
try {
comment.setComment(decrypt(comment.getComment(), mPassword));
} catch (Exception e) {
e.printStackTrace();
}
mCommentList.add(comment);
keysList.add(dataSnapshot.getKey());
mCommentAdapter.notifyItemInserted(mCommentList.size() - 1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = keysList.indexOf(dataSnapshot.getKey());
mCommentList.remove(index);
keysList.remove(index);
mCommentAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
reference.addChildEventListener(childEventListener);
}
I have seen your code and found that you are making mistake by fetching data from firebase by creating methods in the adapter and calling it from onBindViewHolder.
I am currently working with firebase realtime database and I had faced the same problem like you before 3 months and the solution i have used is working fine.
You should have to use asyncTask inside recycler view adapter. Please have a look at my code, this may help you.
Feel free to ask me if you need any help regarding android and firebase
ChooserAdapter.java
public class ChooserAdapter extends RecyclerView.Adapter<ViewHolder> {
ArrayList<Bean> list;
Context context;
public ChooserAdapter(ArrayList<DoctorList> list, Context context) {
this.listFiltered = list;
this.list = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.bean = list.get(position);
holder.asyncTask = new AsyncTask(holder,holder.bean.getId());
holder.asyncTask.execute();
}
#Override
public int getItemCount() {
return list.size();
}
public ArrayList<List> adapterList() {
return list;
}
public List getItem(int position) {
return list.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txtTitle)
TextView txtTitle;
AsyncTask asyncTask;
Bean bean;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
static class AsyncTask extends AsyncTask<Void, Integer, String> {
ViewHolder viewHolder;
String Id;
DatabaseReference dbRef;
AsyncTask(ViewHolder viewHolder, String Id) {
this.viewHolder = viewHolder;
this.Id = Id;
dbRef = FirebaseDatabase.getInstance().getReference("FcmNode");
dbRef.keepSynced(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
if (!isCancelled())
dbRef.orderByChild("Id").equalTo(Id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String name = dataSnapshot.getValue(String.class);
viewHolder.txtTitle.setText(name);
viewHolder.txtTitle.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return "";
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
}
}
}
I am trying to learn to create a chat Activity and trying to retrieve all the message from the firebase when I send the message then the message is been stored in the firebase but at the time to receiving on the single message is been received.i am unable to understand the problem my code
personalChat.java//onstart method
protected void onStart() {
super.onStart();
rootRef.child("Message").child(CurrentUserId).child(msgReciverId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
message cMessage = dataSnapshot.getValue(message.class);
messageList.add(cMessage);
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) {
}
});
}
message_adapter.java
public class message_adapter extends RecyclerView.Adapter<message_adapter.MessageViewHolder> {
private List<message> usermsgList;
private FirebaseAuth mAuth;
private DatabaseReference userref;
public message_adapter(List<message> usermsgList){
this.usermsgList = usermsgList;
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.coustommsglayout,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder holder, int position) {
String msgsenderid = mAuth.getCurrentUser().getUid();
message Message = usermsgList.get(position);
String fromuserid = Message.getFfrom();
String fromMessageType = Message.getType();
userref = FirebaseDatabase.getInstance().getReference().child("User").child(fromuserid);
userref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")){
String reciverimage = dataSnapshot.child("image").getValue().toString();
//Picasso.get().load(reciverimage).into(holder.reciverProfileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (fromMessageType.equals("Text")){
holder.recivermsgtext.setVisibility(View.INVISIBLE);
holder.reciverProfileImage.setVisibility(View.INVISIBLE);
if (fromuserid.equals(msgsenderid)){
holder.sendermsgtext.setBackgroundResource(R.drawable.sendermsglayout);
holder.sendermsgtext.setText(Message.getMessage());
}else{
holder.sendermsgtext.setVisibility(View.INVISIBLE);
holder.recivermsgtext.setVisibility(View.VISIBLE);
holder.reciverProfileImage.setVisibility(View.VISIBLE);
holder.recivermsgtext.setBackgroundResource(R.drawable.recivermsglayout);
holder.recivermsgtext.setText(Message.getMessage());
}
}
}
#Override
public int getItemCount() {
return usermsgList.size();
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView sendermsgtext,recivermsgtext;
public CircleImageView reciverProfileImage;
public MessageViewHolder(#NonNull View itemView){
super(itemView);
sendermsgtext = (TextView) itemView.findViewById(R.id.sender);
recivermsgtext = (TextView) itemView.findViewById(R.id.reciver);
reciverProfileImage = (CircleImageView) itemView.findViewById(R.id.profile_msg_dp);
}
}
}
it should show all the msg available in the Message.child(currentuser).child(reciveruserid). but it only shows the first value. Please help me out with this problem
firebase Message node
Message
JsmvpdGLjLbg9mQ0TfmKForis5q2
PnYKrGiS7YUp9JdHNDMurOSbGBw1
-LoHAND5o_T8S2NRECAH
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "hello"
type: "Text"
-LoJCo9T7IrkHxD5xlZR
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "whtsup"
type: "Text"
-LoJE04JSfl3BPyU3r9T
ffrom: "JsmvpdGLjLbg9mQ0TfmKForis5q2"
message: "wtsup"
type: "Text"
I have a database structure like this:
"users": {
"school": {
userId (randomkey) {
"email": "email#emai.email"
"provider": "provider"
}
}
}
I'm using a recycler view where users can add each other to a group. I'm showing the email for the user in the recycler view and that works fine. But the problem is that I need to retrieve the userId key for the email that is clicked on and append that to a List that I then push to firebase. I'm doing all that with this code.
Adapter class
class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemClickListenerPeopleToAdd itemClickListenerPeopleToAdd;
public TextView emailLbl;
public RecyclerViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
emailLbl = (TextView) itemView.findViewById(R.id.emailLbl);
}
public void setItemClickListenerPeopleToAdd(ItemClickListenerPeopleToAdd itemClickListenerPeopleToAdd) {
this.itemClickListenerPeopleToAdd = itemClickListenerPeopleToAdd;
}
#Override
public void onClick(View v) {
itemClickListenerPeopleToAdd.onClick(v, getAdapterPosition());
}
}
public class PeopleToAddAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private static final String TAG = "Working";
public ArrayList<String> peopleList = new ArrayList<String>();
private List<ModelProject> mModelList;
public PeopleToAddAdapter(List<ModelProject> modelList) {
mModelList = modelList;
}
private Context context;
private List<PeopleToAdd> mPeopleToAdd;
public List<PeopleToAdd> mList;
public PeopleToAddAdapter(Context con, List<PeopleToAdd> list) {
this.context = con;
this.mPeopleToAdd = list;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.people_to_add_listview, parent, false);
return new RecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
final PeopleToAdd listItem = mPeopleToAdd.get(position);
holder.emailLbl.setText(listItem.getEmail());
holder.setItemClickListenerPeopleToAdd(new ItemClickListenerPeopleToAdd() {
#Override
public void onClick(View view, int position) {
Toast.makeText(context, "Click" + listItem.getEmail(), Toast.LENGTH_SHORT).show();
peopleList.add(listItem.toString());
Log.d("value", String.valueOf(peopleList));
}
});
}
#Override
public int getItemCount() {
return mPeopleToAdd.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView emailLbl;
public MyViewHolder(View itemView) {
super(itemView);
emailLbl = (TextView) itemView.findViewById(R.id.emailLbl);
}
}
}
PeopleToAdd
public class PeopleToAdd {
private String email;
private String provider;
public PeopleToAdd(String email, String provider) {
this.email = email;
this.provider = provider;
}
public PeopleToAdd() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
Activity class
listItems = new ArrayList<>();
schoolList = new ArrayList<>();
adapter = new PeopleToAddAdapter(this, listItems);
recyclerView.setAdapter(adapter);
mGetSchool = mDatabase.getReference().child("users").child(mCurrentUserId).child("schoolName");
protected void onStart() {
super.onStart();
mGetSchool.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
childPath = dataSnapshot.getValue(String.class);
//peopleAddedTxtView.setText(childPath);
mPeopleToAdd = mDatabase.getReference().child("users").child(childPath);
mPeopleToAdd.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
listItems.add(peopleToAdd);
test = dataSnapshot.getKey();
Log.d(TAG, test);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.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) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I'm somehow getting a strange path as the userID
example: "com.appName.Services.PeopleToAdd#ca8f01". How can I get the right userId (the random key generated by firebase). I have it in the "test" String in activity but how can I add that to the List when a user clicks on that user in the reyclerView. I hope you understand me. Thank you in advance.
A snapshot contains two main things: the key from where the data was loaded, and the value that was loaded. Right now your onChildAdded only uses the value, and throws the key away:
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
listItems.add(peopleToAdd);
test = dataSnapshot.getKey();
Log.d(TAG, test);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.notifyDataSetChanged();
}
And since you need the key later in your code, you can't retrieve it anymore. The value doesn't contain the key.
One solution is to add the key to you PeopleToAdd class. Based on the answer I gave to Is there a way to store Key in class which I cast from Firebase object?, that could look like this for you:
public class PeopleToAdd {
#Exclude
public String key;
private String email;
private String provider;
public PeopleToAdd(String email, String provider) {
this.email = email;
this.provider = provider;
}
public PeopleToAdd() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
And then modify your onChildAdded to set the key on the PeopleToAdd it instantiated from the value:
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
PeopleToAdd peopleToAdd = dataSnapshot.getValue(PeopleToAdd.class);
peopleToAdd.key = dataSnapshot.getKey();
listItems.add(peopleToAdd);
peopleToAddAdapter = new PeopleToAddAdapter(SetProject.this, listItems);
recyclerView.setAdapter(peopleToAddAdapter);
peopleToAddAdapter.notifyDataSetChanged();
}
Now you can get the key of the PeopleToAdd from its key field.
I'm trying to retrieve comments from the database but it shows all the comments as duplicate
This same listner works fine with fragments but gives duplicate item bug when implemented on Activity
private void startListening() {
Query query = mCommentsDatabase;
FirebaseRecyclerOptions<Comment> options =
new FirebaseRecyclerOptions.Builder<Comment>()
.setQuery(query, Comment.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Comment, CommentsViewHolder>(options){
#Override
public CommentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.single_comment_item, parent, false);
return new CommentsViewHolder(view);
}
#Override
protected void onBindViewHolder(final CommentsViewHolder holder, int position, final Comment model) {
mCommentsDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists() && dataSnapshot != null){
if (dataSnapshot.exists()){
String CommenterId = dataSnapshot.child("uid").getValue().toString();
mUsersDatabase.child(CommenterId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot userDataSnapshot) {
if (userDataSnapshot.exists()){
String username = userDataSnapshot.child("username").getValue().toString();
String thumbImage = userDataSnapshot.child("profile_thumbnail").getValue().toString();
String comment = dataSnapshot.child("body").getValue().toString();
Long timestamp = Long.parseLong(dataSnapshot.child("timestamp").getValue().toString());
GetTimeAgo getTimeAgo = new GetTimeAgo();
String time = getTimeAgo.getTimeAgo(timestamp, getApplicationContext());
holder.setName(username);
holder.setComment(comment);
holder.setImage(thumbImage, getApplicationContext());
holder.setTime(time);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#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) {
}
});
}
};
mCommentsList.setAdapter(adapter);
adapter.startListening();
}
Can someone help point to what's wrong?
I've implemented the same thing in fragments it's working but when used in an Activity it works weirdly.
I have an array of username(ids) which i need to search using Firebase Database and rendering using Firebase UI, the way that i am doing it is only showing the last user and not all of the users that have those ids. I need to render the cards or all the users with different ids.
This is my class
public class UserMessageListFragment extends Fragment {
private ProgressDialog progressDialog;
private final String TAG = "UsersMessageList";
private RecyclerView mResultList;
private ArrayList<String> arrayUsers;
public static UserMessageListFragment newInstance() {
return new UserMessageListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_message_list, container, false);
mResultList = view.findViewById(R.id.message_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(mResultList.getContext()));
final DatabaseReference refMessages = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("usuarios");
refMessages.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.getKey().contains(UserDetails.username+ "_")) {
String[] userChatWithId = dataSnapshot.getKey().split(UserDetails.username+"_");
final Query firebaseSearchQuery = ref.orderByChild("username").equalTo(userChatWithId[1]);
final FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(firebaseSearchQuery, User.class)
.build();
bindAndBuildFirebaseUi(options);
}
}
#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) {
}
});
// progressDialog = new ProgressDialog(getContext());
// progressDialog.setMessage("Carregando...");
// progressDialog.show();
return view;
}
public void bindAndBuildFirebaseUi(FirebaseRecyclerOptions options) {
final FirebaseRecyclerAdapter<User, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<User, UsersViewHolder>(options) {
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_list_layout, parent, false);
return new UsersViewHolder(v);
}
#Override
protected void onBindViewHolder(final UsersViewHolder holder, int position, final User model) {
holder.bind(model);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserDetails.chatWithId = model.getUsername();
UserDetails.chatWith = model.getName();
startActivity(new Intent(getContext(), Chat.class));
}
});
}
};
firebaseRecyclerAdapter.startListening();
mResultList.setAdapter(firebaseRecyclerAdapter);
}
}
at this line
final Query firebaseSearchQuery = ref.orderByChild("username").equalTo(userChatWithId[1]);
there will be different values inside userChatWithid1, however FirebaseUI is rendering only the last one.
I am starting to hate FirebaseUI because i've been having so many issues with it.
Can anybody help me, please???
You're doing some very unconventional stuff... FirebaseUI will handle all the database listeners and queries for you. All you should do is pass in the root node that contains all your users and the rest will be taken care of. (I believe in your case it's usuarios so ref will do the trick.) I'd recommend reading the docs: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md