I'm new to android and I wanted to create a chat in my app, it's like a global roomchat based on firebase. Messages are displayed via RecyclerView and the problem is that when it's loaded the images of people, their names are somehow mixed up. When I go back to previous activity and open the chat activity again everything becomes OK. But the when a new message is added the rows shuffle again. I'm sure that it should be very ease to fix, but I can't...Please help. Thank you!
This is the chat activity oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_chat);
main_recycler_view = (RecyclerView) findViewById(R.id.messages_list);
main_recycler_view.setVisibility(View.GONE);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
}
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
sendToStart();
} else {
mUserRef.child("online").setValue("true");
String transp = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ftransp.png?alt=media&token=fc7b2315-f24b-453a-926e-364fff55e31b";
mUserRef.child("version").setValue(transp);
mToolbar = (Toolbar) findViewById(R.id.chattb);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.chat_title);
imageButton_send = (Button) findViewById(R.id.chat_send_btn);
editText_message = (EditText) findViewById(R.id.chat_message_view);
database = FirebaseDatabase.getInstance();
databaseRef = database.getReference();
mContext = (MainChatPage.this);
adapter = new MainAdapter(mContext, messageArrayList);
main_recycler_view.setAdapter(adapter);
main_recycler_view.setLayoutManager(new LinearLayoutManager(c));
databaseRef.child("the_messages").limitToLast(50).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
progressBar.setVisibility(View.GONE);
main_recycler_view.setVisibility(View.VISIBLE);
final Message new_message = dataSnapshot.getValue(Message.class);
final String userid = dataSnapshot.child("userID").getValue().toString();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userid).exists()) {
messageArrayList.remove(new_message);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
main_recycler_view.scrollToPosition(adapter.getItemCount() - 1);
messageArrayList.add(new_message);
adapter.notifyDataSetChanged();
}
#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) {
}
});
My adapter:
public MainAdapter(MainChatPage context, ArrayList<Message> data) {
this.data = data;
this.mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_single_layout, null);
message_profile_layout = (CircleImageView) view.findViewById(R.id.message_profile_layout);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {
final Message message = data.get(i);
final String userid = message.getUserID();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String thumb = dataSnapshot.child("thumb_image").getValue().toString();
String nome = dataSnapshot.child("name").getValue().toString();
String dialog_name = nome;
String vers = dataSnapshot.child("version").getValue().toString();
//String proic = "https://firebasestorage.googleapis.com/v0/b/chatqs-a4c10.appspot.com/o/profile_images%2Ficonfinder-pro-icon-icon.png?alt=media&token=1ca05e32-f3e7-4f73-af54-2be17ad0fed6";
// Picasso.with(myViewHolder.mes_proicon.getContext()).load(proic)
// .placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
// myViewHolder.name_text_layout.setText(nome);
Picasso.with(myViewHolder.message_profile_layout.getContext()).load(thumb)
.placeholder(R.drawable.default_avatar).into(myViewHolder.message_profile_layout);
Picasso.with(myViewHolder.mes_proicon.getContext()).load(vers)
.placeholder(R.drawable.transp).into(myViewHolder.mes_proicon);
myViewHolder.name_text_layout.setText(nome);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
String formatted_date = SCUtils.formatted_date(message.getTimestamp());
myViewHolder.message_text_layout.setText(Html.fromHtml(message.getMessage()));
myViewHolder.time_text_layout.setText(Html.fromHtml(formatted_date));
myViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userid.equals(current_uid)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
LayoutInflater inflater = mContext.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog, null);
TextView dialog_name = (TextView) dialogView.findViewById(R.id.dialog_name);
CircleImageView dialog_icon = (CircleImageView) dialogView.findViewById(R.id.dialog_icon);
builder.setView(dialogView);
dialog_name.setText(myViewHolder.name_text_layout.getText());
dialog_icon.setImageDrawable(myViewHolder.message_profile_layout.getDrawable());
builder.setPositiveButton(R.string.block, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("blocked");
mDatabase.child(userid).push().setValue("");
}
})
.setNegativeButton(R.string.open_profile, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent chatIntent = new Intent(mContext, UserProfileActivity.class);
chatIntent.putExtra("user_id", userid);
mContext.startActivity(chatIntent);
mContext.finish();
}
});
builder.show();
} else {
Intent Intent = new Intent(mContext, ProfileFragment.class);
mContext.startActivity(Intent);
mContext.finish();
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mView;
protected TextView message_text_layout;
protected TextView name_text_layout;
protected TextView time_text_layout;
protected CircleImageView message_profile_layout;
protected CircleImageView mes_proicon;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
this.message_text_layout = (TextView) mView.findViewById(R.id.message_text_layout);
this.name_text_layout = (TextView) mView.findViewById(R.id.name_text_layout);
this.time_text_layout = (TextView) mView.findViewById(R.id.time_text_layout);
this.mes_proicon = (CircleImageView) mView.findViewById(R.id.mes_proicon);
this.message_profile_layout = (CircleImageView) mView.findViewById(R.id.message_profile_layout);
}
}
just remove .placeholder. I dont know why but sometimes it happens because of this method
Related
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);
}
}
}
I have an android app where users submit their posts and only them can view what they posted. I achieved that using the code below
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("reports").child(uid);
However I have a separate admin app where i want to see what all the users post but i cant be able to achieve that. Please help
below is an image of my database
mDatabase = FirebaseDatabase.getInstance().getReference().child("reports") will get all reports for you.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference reportsRef = rootRef.child("reports");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String, Object> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String docId = ds.getKey();
list.add(docId);
Log.d("TAG", docId);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
reportsRef.addListenerForSingleValueEvent(eventListener);
Here is my code
public class MyReports extends Fragment {
private RecyclerView mBlogList;
private GridLayoutManager gridLayoutManager;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private boolean mProcessLike = false;
public MyReports() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_reports, container, false);
mAuth =FirebaseAuth.getInstance();
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(getActivity(), Login.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("reports");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike =FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mBlogList = (RecyclerView) view.findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
MyReports.BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(MyReports.BlogViewHolder viewHolder, Blog model, final int position) {
final String post_key =getRef(position).getKey();
viewHolder.setOutreach(model.getOutreach());
viewHolder.setDate(model.getDate());
viewHolder.setNamee(model.getNamee());
viewHolder.setPhone(model.getPhone());
viewHolder.setPartici(model.getPartici());
viewHolder.setLesson(model.getLesson());
viewHolder.setImage(getActivity().getApplicationContext(),model.getImage());
viewHolder.setImage1(getActivity().getApplicationContext(),model.getImage1());
viewHolder.setImage2(getActivity().getApplicationContext(),model.getImage2());
viewHolder.setImage3(getActivity().getApplicationContext(),model.getImage3());
viewHolder.setImage4(getActivity().getApplicationContext(),model.getImage4());
viewHolder.setLikeBtn(post_key);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(getActivity(), post_key, Toast.LENGTH_SHORT).show();
Intent singleBlogIntent = new Intent(getActivity(), PostSingleActivity.class);
singleBlogIntent.putExtra("blog_id", post_key);
startActivity(singleBlogIntent);
}
});
viewHolder.mLikebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
if(mProcessLike){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
}else {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mLikebtn;
DatabaseReference mDatabaseLike;
FirebaseAuth mAuth;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
mLikebtn = (ImageButton) mView.findViewById(R.id.like_btn);
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth = FirebaseAuth.getInstance();
mDatabaseLike.keepSynced(true);
}
public void setLikeBtn(final String post_key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mLikebtn.setImageResource(R.drawable.ic_new_like_blue);
}else {
mLikebtn.setImageResource(R.drawable.ic_new_like_red2);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setOutreach(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_outreach);
post_title.setText(title);
}
public void setDate(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_date);
post_desc.setText(desc);
}
public void setNamee(String username){
TextView post_username = (TextView) mView.findViewById(R.id.post_namee);
post_username.setText(username);
}
public void setPhone(String date){
TextView post_date = (TextView) mView.findViewById(R.id.post_phone);
post_date.setText(date);
}
public void setPartici(String phone){
TextView post_phone = (TextView) mView.findViewById(R.id.post_partici);
post_phone.setText(phone);
}
public void setLesson(String date){
TextView post_date = (TextView) mView.findViewById(R.id.post_lesson);
post_date.setText(date);
}
public void setImage(Context ctx, String image){
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
public void setImage1(Context ctx, String image1){
ImageView post_image1 = (ImageView) mView.findViewById(R.id.post_image1);
Picasso.with(ctx).load(image1).into(post_image1);
}
public void setImage2(Context ctx, String image2){
ImageView post_image2 = (ImageView) mView.findViewById(R.id.post_image2);
Picasso.with(ctx).load(image2).into(post_image2);
}
public void setImage3(Context ctx, String image3){
ImageView post_image3 = (ImageView) mView.findViewById(R.id.post_image3);
Picasso.with(ctx).load(image3).into(post_image3);
}
public void setImage4(Context ctx, String image4){
ImageView post_image4 = (ImageView) mView.findViewById(R.id.post_image4);
Picasso.with(ctx).load(image4).into(post_image4);
}
}
public void onResume(){
super.onResume();
// Set title bar
((MainActivity) getActivity())
.setActionBarTitle("Reports");
}
}
I want to hide the current user in RequestsFragment in recyclerview. I tried to setVisibility feature. The current user's informantions are not seen to him. But there is a space still in recyclerview. How can i also delete space between other items. I mean if I have sent a request to other users I dont want to see myself at requests fragment.
public class RequestsFragment extends Fragment {
private RecyclerView recyclerView_friendRequestsList;
private View mainView;
private DatabaseReference friendRequestsDatabaseReference;
private DatabaseReference usersDatabaseReference;
private FirebaseAuth firebaseAuth;
private String current_user_id;
public RequestsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.fragment_requests, container, false);
recyclerView_friendRequestsList = mainView.findViewById(R.id.friendRequests_list);
recyclerView_friendRequestsList.setHasFixedSize(true);
recyclerView_friendRequestsList.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseAuth = FirebaseAuth.getInstance();
current_user_id = firebaseAuth.getCurrentUser().getUid();
friendRequestsDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friend Requests");
friendRequestsDatabaseReference.keepSynced(true);
usersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
usersDatabaseReference.keepSynced(true);
return mainView;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<FriendRequests, RequestsFragment.FriendRequestsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<FriendRequests, FriendRequestsViewHolder>(
FriendRequests.class,
R.layout.users_single_layout,
RequestsFragment.FriendRequestsViewHolder.class,
friendRequestsDatabaseReference
) {
#Override
protected void populateViewHolder(final FriendRequestsViewHolder viewHolder, FriendRequests model, final int position) {
final String user_id = getRef(position).getKey();
friendRequestsDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
usersDatabaseReference.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!user_id.equals(current_user_id)) {
final String user_displayName = dataSnapshot.child("display_name").getValue().toString();
final String user_thumbImage = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
viewHolder.setUserOnline(userOnline);
}
viewHolder.setName(user_displayName);
viewHolder.setImage(user_thumbImage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
} else {
viewHolder.mView.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
friendRequestsDatabaseReference.child(current_user_id).child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("request_type")) {
String request_type = dataSnapshot.child("request_type").getValue().toString();
viewHolder.setRequest_type(request_type);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
recyclerView_friendRequestsList.setAdapter(firebaseRecyclerAdapter);
}
public static class FriendRequestsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendRequestsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView userNameView = mView.findViewById(R.id.user_single_displayName);
userNameView.setText(name);
}
public void setRequest_type(String request_type) {
TextView userStatusView = mView.findViewById(R.id.user_single_status);
userStatusView.setText(request_type);
}
public void setImage(final String thumb_image) {
CircleImageView userImageView = mView.findViewById(R.id.user_single_image);
Picasso.get().load(thumb_image).placeholder(R.mipmap.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = mView.findViewById(R.id.user_single_online);
if (online_status.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
I was following a tutorial on youtube to make a chat app and this fragment shows the list of friends but this method cant be used anymore. I have tried my whole night putting up the code together but couldn't.
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
// I have tried using options here but i failed*
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
// This method is no more available
#Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
I'm kinda newbie to Android.
I have a recyclerview that I store in Firebase database.
My recyclerview are made of cardviews.
Inside each cardview I have a button that updates the node info in Firebase.
Each time the above is happening, my page refreshes (I guess to load the new data).
My mainactivity code relevant code(called on onCreate) :
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my adapter :
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
public static Boolean isAyed = false;
private FirebaseAuth firebaseAuth;
private List<Post> posts;
private Context context;
private String userTryToAyeEmail;
public RecyclerAdapter(List<Post> posts, Context context) {
this.posts = posts;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
firebaseAuth = FirebaseAuth.getInstance();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_card, parent, false);
return new ViewHolder(v);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Post post = posts.get(position);
holder.imageButton.setVisibility(View.GONE);
holder.editText.setVisibility(View.GONE);
String colorString = post.getPostColor();
int color = Color.parseColor(colorString);
int newNumOfLikes = post.getPostLikes();
int currentNumOfLikes = post.getPostLikes();
// holder.cardView.setCardBackgroundColor(color);
holder.textViewHead.setText(post.getPostContent());
holder.textViewNickname.setText(post.getPostNickname());
holder.textViewTimeStamp.setText(post.getPostTimeStamp());
holder.ayeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean userLiked = false;
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> currentLikedPost = post.getUserLikedList();
for (int i = 0; i < currentLikedPost.size(); i++) {
if (currentUserEmail.equals(currentLikedPost.get(i))) {
currentLikedPost.remove(i);
int newNumOfLikes = post.getPostLikes() - 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
userLiked = true;
break;
}
}
if (!userLiked) {
currentLikedPost.add(currentUserEmail);
int newNumOfLikes = post.getPostLikes() + 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
}
}
}
});
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> usersLikedPost = post.getUserLikedList();
for (int i = 0; i < usersLikedPost.size(); i++) {
if (currentUserEmail.equals(usersLikedPost.get(i))) {
holder.ayeButton.setTextColor(Color.parseColor("#FF0000"));
break;
}
}
}
holder.ayeTextView.setText(Integer.toString(newNumOfLikes));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(context, SinglePostActivity.class);
myIntent.putExtra("postID", post.getId());
myIntent.putExtra("postNickname", post.getPostNickname());
myIntent.putExtra("postTimeStamp", post.getPostTimeStamp());
myIntent.putExtra("postContent", post.getPostContent());
myIntent.putExtra("postColor", post.getPostColor());
context.startActivity(myIntent);
}
});
}
private void updateLikes(String id, int newNumOfLikes, String postNickname, String postTimeStamp, String postContent, String postColor, String SubGenre, List<String> userLikedPostList) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("posts").child(id);
Post post = new Post(postColor, postContent, postNickname, postTimeStamp, id, newNumOfLikes, SubGenre, userLikedPostList);
databaseReference.setValue(post);
}
#Override
public int getItemCount() {
return posts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewNickname;
public TextView textViewTimeStamp;
public TextView ayeButton;
public TextView ayeTextView;
public CardView cardView;
public LinearLayout linearLayout;
public EditText editText;
public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewNickname = (TextView) itemView.findViewById(R.id.textViewNickname);
textViewTimeStamp = (TextView) itemView.findViewById(R.id.textViewTimeStamp);
ayeButton = (TextView) itemView.findViewById(R.id.ayeButton);
ayeTextView = (TextView) itemView.findViewById(R.id.ayeTextView);
cardView = (CardView) itemView.findViewById(R.id.cardViewID);
linearLayout = (LinearLayout) itemView.findViewById(R.id.cardLinearLayout);
editText = (EditText) itemView.findViewById(R.id.addCommentEditText);
imageButton = (ImageButton) itemView.findViewById(R.id.addCommentImageButton);
}
}
}
I wish the page to stay in place, how can I do that ??
Thank you all.
Set your adapter in onCreate and notify it from onDataChange
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//initialize
.
.
//set adapter
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter.notifyDataSetChanged(); //notify
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}