Firebase syncing method not syncing - android

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?

Related

FirebaseRecyclerAdapter model returning null values

I'm trying to make a comment system for posts on my social media app. In my database each post has a section inside of "comments" table, like so:
"hypno--######" is the title of the social media post. It Contains the comment, user id of the user who posted the comment, and a unixtimestamp when the comment was posted. Each comment is titled after the time it was posted.
This is the Comment class
public class comment {
public String uID;
public String comment_t;
public long unixTimestamp;
public comment() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public comment(String uID, String comment_t, long unixTimestamp) {
this.uID = uID;
this.comment_t = comment_t;
this.unixTimestamp = unixTimestamp;
}
public String getuID() {
return uID;
}
public void setuID(String uID) {
this.uID = uID;
}
public String getComment() {return comment_t;}
public void setComment() {this.comment_t = comment_t; }
public long getUnixTimestamp() {
return unixTimestamp;
}
}
This is the Comment Adapter:
Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {
private DatabaseReference mDatabase;
private static final String TAG = "RecyclerViewAdapter";
private Context mContext;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private static AppCompatActivity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (AppCompatActivity) context;
}
public Adapter_Comment(#NonNull FirebaseRecyclerOptions<comment> options) {
super(options);
//this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder_com onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
return new ViewHolder_com(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder_com holder, int position, #NonNull comment model) {
mDatabase = FirebaseDatabase.getInstance().getReference();
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
holder.postPfp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//AppCompatActivity activity = (AppCompatActivity) v.getContext();
AppCompatActivity activity = unwrap(v.getContext());
Fragment OtherProfileFragment = new OtherProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("key", model.getuID());
OtherProfileFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
}
});
}
public class ViewHolder_com extends RecyclerView.ViewHolder {
TextView comment_text;
CircleImageView postPfp;
TextView time;
RelativeLayout comment_layout;
public ViewHolder_com(#NonNull View itemView) {
super(itemView);
postPfp = itemView.findViewById(R.id.iv_comment_icon);
comment_text = itemView.findViewById(R.id.tv_comment_text);
time = itemView.findViewById(R.id.tv_comment_time);
comment_layout = itemView.findViewById(R.id.comment_layout);
}
}
}
This is Comment Fragment:
public class CommentFragment extends Fragment {
private DatabaseReference mDatabase;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
View view;
String value;
RecyclerView recyclerView;
Query query;
TextView comment_text;
long unixTime = System.currentTimeMillis() / 1000L;
public long globalUnix;
Button comment_post;
String comment_string;
Adapter_Comment adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_comment, container, false);
value = getArguments().getString("key");
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.recyclerv_comment);
comment_text = view.findViewById(R.id.tv_comment_type);
comment_post = view.findViewById(R.id.btn_comment_post);
globalUnix = (unixTime * -1);
comment_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(comment_text.getText().toString() == NULL){
Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
}
else{
comment com = new comment();
com.uID = user.getUid();
com.comment_t = comment_text.getText().toString();
com.unixTimestamp = globalUnix;
mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);
}
}
});
initRecyclerView();
return view;
}
private void initRecyclerView(){
//Log.d(TAG, "initRecyclerView: init recyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();
FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();
adapter = new Adapter_Comment(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Inside of the adapter I'm using the comment model, to get the uID, comment and timestamp to fill the holder, however when i set these values im getting null values. Is there something im missing when trying to connect the adapter/firebase and model/holder?
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
There's really too much going on in here, but...
As far as I can see you're creating a FirebaseUI adapter on FirebaseDatabase.getInstance().getReference().child("comments"). FirebaseUI adapters show the direct child nodes of the node you pass in, so in your case it'll create one view for the hypno---...196 node. You're trying to read a Comment object from there, but don't exist until one level lower in your JSON.
So you can:
Either show the comments for one post, by basing the adapter off of that. So: FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196") (which the real key in there).
Or you can show one piece of information about each post, for example its key.
If you want to show a flat list of comments for all posts through the FirebaseUI adapter, you'll have to store a flat list of comments across all posts in your database too.

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

How to hide particular item in RecyclerView and deleting its space

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

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