How to hide particular item in RecyclerView and deleting its space - android

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

Related

Sorting recycler view items according to most recent message

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

Retrieve all data from firebase where users' posts are in uid

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

Firebase syncing method not syncing

Code
public class HomeScreen_Friends extends Fragment {
private View rootView;
private String userName;
private String UID;
private TextView noUsersText;
private ProgressDialog mProgressDialogue;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabaseReference;
private DatabaseReference mUsersDatabase;
private RecyclerView mUsersList;
private FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_friends, container, false);
noUsersText = (TextView) rootView.findViewById(R.id.noUsersText);
mUsersList = (RecyclerView) rootView.findViewById(R.id.usersList);
mUsersList.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.HORIZONTAL));
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
UID = mAuth.getCurrentUser().getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(UID);
mDatabaseReference.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("UserData");
mUsersDatabase.keepSynced(true);
mProgressDialogue = new ProgressDialog(getActivity());
mProgressDialogue.setMessage("Loading...");
mProgressDialogue.show();
mUsersList.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerOptions<AllUsersHelper> options =
new FirebaseRecyclerOptions.Builder<AllUsersHelper>()
.setQuery(mDatabaseReference, AllUsersHelper.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final UsersViewHolder holder, int position, #NonNull AllUsersHelper model) {
holder.setName(model.getName());
holder.setStatus(model.getStatus());
holder.setImage(model.getImage());
final String userId = getRef(position).getKey();
mUsersDatabase.orderByChild("Name");
mUsersDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mName = dataSnapshot.child("Name").getValue().toString();
String mStatus = dataSnapshot.child("Status").getValue().toString();
String mDisplayImage = dataSnapshot.child("Image").getValue().toString();
if(dataSnapshot.hasChild("Online")) {
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setUserOnline(userOnline);
}
holder.setName(mName);
holder.setImage(mDisplayImage);
holder.setStatus(mStatus);
mProgressDialogue.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("UserData").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("Name").getValue().toString();
Intent intent = new Intent(getActivity(), Chat.class);
intent.putExtra("Recievers_Id", userId);
intent.putExtra("Recievers_Name", userName);
startActivity(intent);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_activity_all_users, parent, false);
return new UsersViewHolder(view);
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
return rootView;
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
public View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView mDisplayName = (TextView) mView.findViewById(R.id.display_name);
mDisplayName.setText(name);
}
public void setStatus(String status) {
TextView mDisplayStatus = (TextView) mView.findViewById(R.id.display_status);
mDisplayStatus.setText(status);
}
public void setImage(String image) {
CircularImageView mDisplayImage = (CircularImageView) mView.findViewById(R.id.circleImageView);
Picasso.get().load(image).into(mDisplayImage);
}
public void setUserOnline(String userOnline) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.online);
if(userOnline.equals("Online")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if(firebaseRecyclerAdapter != null) {
firebaseRecyclerAdapter.stopListening();
}
}
}
Where should i put the keepSynced method for retrieving data offline because i tried below the database reference and it still doesn't show my data when i have no internet. Can someone help me out please... Also if the resukt is null how can i stop the progress dialog and show a text which says there are no users.
Right now you're just telling Firebase to keep an empty listener active on your Friends and UserData nodes. This ensures that the data from these nodes is always kept up to date (even when you don't attach any other listeners), but the data is still only kept in memory.
To persist the memory cache to disk, so that it can be reloaded in case you don't have an internet connection when starting the app, you'll need to call FirebaseDatabase.getInstance().setPersistenceEnabled(true) when the app starts. See enabling disk persistence in the Firebase docs.
Also see:
Firebase : What is the difference between setPersistenceEnabled and keepSynced?

RecylerView Adapter in android Firebase is not quite syncing

I am creating a program, where user can update post, and other user and same user can react there. For that, I have implemented the love button. So this works this way, I have saved a unique id in the DatabaseReference and other reference for uniquekey for easiness. So, whenever, the user clicks on love button, it must update the total reaction of the node by increasing it to one. The problem I am getting is, whenever I press the love button key, it doesn't call the uniqueID I need. The uniqueId I am getting from model class from viewholder is not the post I have reacted to.
public class LatestFragment extends Fragment {
private RecyclerView latestFragmentRecyclerView;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mAuth;
private static Context context;
private static boolean firstTime;
private static String totalVotes;
private static String uniqueKey;
private static DatabaseReference reactionDatabaseReference;
private static DatabaseReference uniqueKeysReferences;
private static Boolean userReactState;
private static List<String> allUniqueKeys;
public LatestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_latest,container,false);
latestFragmentRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerViewForLatestFragment);
latestFragmentRecyclerView.setHasFixedSize(true);
userReactState = false;
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
latestFragmentRecyclerView.setLayoutManager(layoutManager);
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
reactionDatabaseReference=FirebaseDatabase.getInstance().getReference().child("PostReactions");
uniqueKeysReferences = FirebaseDatabase.getInstance().getReference().child("UniqueKeys");
mDatabaseReference.keepSynced(true);
firstTime = true;
return v;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<Posts, PostViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Posts, PostViewHolder>(
Posts.class, R.layout.each_post_layout, PostViewHolder.class, mDatabaseReference
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder,final Posts model, int position) {
Context c = getActivity();
context = c;
uniqueKey = model.getUnique();
viewHolder.setUsername(model.getUsername());
viewHolder.setCaption(model.getCaption());
viewHolder.setTime(model.getTime());
viewHolder.setImage(model.getImage(),c);
viewHolder.setCurrentUserImage(model.getUserPhoto(),c);
viewHolder.imageViewIfUserClicked(model.getCurrentUserReaction(),c);
totalVotes = model.getTotalReactions();
}
};
latestFragmentRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
View theRecyclingView;
private Button loveButton ;
public PostViewHolder(View itemView) {
super(itemView);
theRecyclingView = itemView;
loveButton = (Button) theRecyclingView.findViewById(R.id.loveButton);
loveButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId()==loveButton.getId())
{
allUniqueKeys = new ArrayList<>();
int position = getAdapterPosition();
Log.e("UniqueKey", String.valueOf(position));
uniqueKeysReferences.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot x : dataSnapshot.getChildren()) {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(firstTime==true)
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
firstTime = false;
int vote= Integer.valueOf(totalVotes);
vote++;
totalVotes = String.valueOf(vote);
reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("true").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
firstTime = true;
int vote= Integer.valueOf(totalVotes);
vote--;
totalVotes = String.valueOf(vote);
reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("false").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public void setUsername(String username)
{
TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.userWhoPostedUserName);
mUsername.setText(username);
}
public void setCaption(String caption) {
TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.captionForPic);
mUsername.setText(caption);
}
public void setImage(final String image, final Context c) {
final ImageView imageView = (ImageView) theRecyclingView.findViewById(R.id.userUploadedImageView);
Picasso.with(c).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(c).load(image).into(imageView);
}
});
}
public void setTime(String time) {
TextView time_of_posting = (TextView) theRecyclingView.findViewById(R.id.timeOfPosting_each_post_layout);
time_of_posting.setText(time);
}
public void setCurrentUserImage(final String userPhoto, final Context c) {
final CircleImageView imageView = (CircleImageView) theRecyclingView.findViewById(R.id.userWhoPostedCircleImageView);
Picasso.with(c).load(userPhoto).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(c).load(userPhoto).into(imageView);
}
});
}
public void imageViewIfUserClicked(String currentUserReaction, final Context c) {
//reactionDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
// #Override
//public void onDataChange(DataSnapshot dataSnapshot) {
// String CurrentuserReaction = dataSnapshot.child(uniqueKey).child("TotalReactions").child("CurrentUserReaction").getValue().toString();
// userReactState = Boolean.parseBoolean(CurrentuserReaction);
//}
//#Override
//public void onCancelled(DatabaseError databaseError) {
//
// }
// });
if(userReactState==false) {
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
}
else
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
}
}
}
}

Firebase timestamp show int number

I am using firebase to view timestamp and after I save the stored the timestamp in my firebase the issue is how to convert the int number value to correctly value like "1 hr" ...
When I retrieve the timestamp it get int number ex:"1487330278409"
here's my value which named "creationDate"
how to get timestamp ex: 3 hours ago, 1 day, just now.
here's my fragment
public class Challenges extends Fragment{
private RecyclerView mPostList;
private DatabaseReference mDatabase,mDatabaseFriends,mDatabaseLike;
private SwipeRefreshLayout mRefreshLayout;
private boolean mProcessLike = false;
private String AA;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mListener;
private Query mQuery;
private FirebaseUser mCurrentUser;
public Challenges() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MultiDex.install(getActivity());}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.challenges, container, false);
mListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser User = firebaseAuth.getCurrentUser();
if (User == null) {
Intent A = new Intent(getActivity(), Login.class);
startActivity(A);}}};
mPostList=(RecyclerView)v.findViewById(R.id.PostList);
mPostList.setHasFixedSize(true);
mPostList.setItemAnimator(new DefaultItemAnimator());
mPostList.setLayoutManager(new LinearLayoutManager(getActivity()));
//AA = getActivity().getIntent().getExtras().getString("QQ");
//Firebase
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseFriends= FirebaseDatabase.getInstance().getReference().child("Friends");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabase.keepSynced(true);
mDatabaseLike.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRefreshLayout=(SwipeRefreshLayout)v.findViewById(R.id.RefreshLayout);
//mQuery = mDatabase.orderByChild("UID").equalTo(String.valueOf(mDatabaseFriends.child(mCurrentUser.getUid()).child("Accepted")));
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
onStart();}});
return v;}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mListener);
mRefreshLayout.setRefreshing(true);
final FirebaseRecyclerAdapter<Getting_Posts, PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Getting_Posts, PostViewHolder>(
Getting_Posts.class, R.layout.post_card_design, PostViewHolder.class, mDatabase) {
#SuppressLint("SetTextI18n")
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Getting_Posts model, int position) {
final String Post_Key = getRef(position).getKey();
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent A = new Intent(getActivity(), com.pcsoftgroup.test.activities.Single_view.class);
A.putExtra("Key", Post_Key);
startActivity(A);}
});
viewHolder.setUsername(model.getUsername());
viewHolder.setProfile(getActivity().getApplicationContext(), model.getProfile());
viewHolder.setDescribe(model.getDescribe());
viewHolder.setWallpaper(getActivity().getApplicationContext(), model.getWallpaper());
viewHolder.setLike(Post_Key);
viewHolder.setLikeNum(Post_Key);
viewHolder.setCommentNum(Post_Key);
viewHolder.mPostTime.setText(model.getTime());
//viewHolder.mPostTime.setText(model.getDate());
//viewHolder.mPostATime.setText(model.getTime());
viewHolder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(Post_Key).hasChild(mCurrentUser.getUid())) {
mDatabaseLike.child(Post_Key).child(mCurrentUser.getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(Post_Key).child(mCurrentUser.getUid()).setValue("LIKED");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//sendIntent.putExtra(Intent.EXTRA_TEXT,viewHolder.mComment.getText().toString());
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent, "Share via");
startActivity(sendIntent);
}
});
mRefreshLayout.setRefreshing(false);
mRefreshLayout.setEnabled(true);
}
};
mPostList.setAdapter(firebaseRecyclerAdapter);}
public static class PostViewHolder extends RecyclerView.ViewHolder{
//Main
View mView;
ImageButton mLike;
ImageButton mCommentBtn;
ImageButton mShare;
//Firebase
TextView mPostTime;
TextView mPostATime;
FirebaseAuth mAuth;
FirebaseUser mCurrentUser;
DatabaseReference mDatabaseLike;
DatabaseReference mDatabaseComment;
public PostViewHolder(View itemView) {
super(itemView);
//Main
mView=itemView;
mPostATime = (TextView) mView.findViewById(R.id.PostATime);
mLike=(ImageButton) mView.findViewById(R.id.PostLike);
mCommentBtn = (ImageButton) mView.findViewById(R.id.PostCommentBtn);
mShare = (ImageButton) mView.findViewById(R.id.PostShare);
mPostTime = (TextView) mView.findViewById(R.id.PostTime);
//Firebase
mAuth =FirebaseAuth.getInstance();
mCurrentUser=mAuth.getCurrentUser();
mDatabaseComment = FirebaseDatabase.getInstance().getReference().child("Comments");
mDatabaseLike= FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseLike.keepSynced(true);
mDatabaseComment.keepSynced(true);
}
//Like
void setLike(final String Post_Key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(Post_Key).hasChild(mCurrentUser.getUid())){
mLike.setImageResource(R.drawable.like_icon);
}else {mLike.setImageResource(R.drawable.unlike_icon);}}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
void setLikeNum(final String Post_Key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String A = String.valueOf(dataSnapshot.child(Post_Key).getChildrenCount());
TextView PostLikeNum = (TextView) mView.findViewById(R.id.PostLikeNum);
PostLikeNum.setText(A);}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
void setCommentNum(final String Post_Key){
mDatabaseComment.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String C = String.valueOf(dataSnapshot.child(Post_Key).getChildrenCount());
TextView PostCommentNum = (TextView) mView.findViewById(R.id.PostCommentNum);
PostCommentNum.setText(C);}
#Override
public void onCancelled(DatabaseError databaseError) {}});}
//Username
public void setUsername(String Username){
TextView PostUsername = (TextView) mView.findViewById(R.id.PostUsername);
PostUsername.setText(Username);}
//Profile
void setProfile(Context ctx2, String Profile){
ImageView PostProfile = (ImageView) mView.findViewById(R.id.PostUserImage);
if (Profile == null){PostProfile.setVisibility(View.VISIBLE);}
else {PostProfile.setVisibility(View.VISIBLE);
Picasso.with(ctx2).load(Profile).resize(120,120).into(PostProfile);}}
//Describe
void setDescribe(String Describe){
TextView PostDescribe = (TextView) mView.findViewById(R.id.PostDesc);
PostDescribe.setText(Describe);}
//Image Load
void setWallpaper(Context ctx, String Image){
ImageView PostWallpaper = (ImageView) mView.findViewById(R.id.PostWallpaper);
if (Image == null){PostWallpaper.setVisibility(View.VISIBLE);}
else {
PostWallpaper.setVisibility(View.VISIBLE);
Picasso.with(ctx).load(Image).resize(1200,600).into(PostWallpaper);}}
}}
and here's my getter and setter java:
public class Getting_Posts {
private String Username;
private String Profile;
private String Describe;
private String Wallpaper;
private String Time;
public Getting_Posts() {
}
public Getting_Posts(String Time, String Username, String Profile, String Describe, String Wallpaper) {
this.Username = Username;
this.Profile = Profile;
this.Describe = Describe;
this.Wallpaper = Wallpaper;
this.Time = Time;
}
public String getDescribe() {
return Describe;
}
public void setDescribe(String describe) {
Describe = describe;
}
public String getWallpaper() {
return Wallpaper;
}
public void setWallpaper(String wallpaper) {
Wallpaper = wallpaper;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getProfile() {
return Profile;
}
public void setProfile(String profile) {
Profile = profile;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
}
Any help please
The retrieved value is a long value representing Milliseconds elapsed since the Epoch time.
You can set this inside a Date object and get the normal human readable version:
Date currentDate = new Date(your_retreived_long_timestamp);
System.out.println(currentDate);
Difference between the currenttimestamp long value and an old timestamp will give the time passed since the old value..
eg : if currenttimestamp - oldtimestamp = 60000
It shows that the oldtimestamp happened a minute ago (60sec * 1000), similarly find the other values as you want
You can then use the current time and the obtained time and find the difference yourself.

Categories

Resources