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");
}
}
Related
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?
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'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
I've recently added a searchBar to my Android Firebase app, but I really can't find how to filter data in my app. I need to search in "title", "desc" and "username" childs, as seen in the
photo.
What should I do? Thanks
[Random letters hsiukhdufhjwrepjèijgitrjwbnrtnbnbeènbèrnbgnèjwtigogjwitjgbniownttngfnwnpnwpjgnjntwjtngjnjwngjggpnwrjgrngjwpnjnvwpjeenjrvnjpreqngjnpwjgnrjpwnjpn2ngj2nrjnp2r2g2hhuheqdhyg1eydgugf]
updated code of MainActivity:
public class MainActivity extends AppCompatActivity{
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private Query mQuery;
private SearchView mSearchView;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private boolean mProcessLike = false;
private TextView badge;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) findViewById(R.id.blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
badge = (TextView)findViewById ( R.id.badge );
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
final FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mQuery
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, Blog model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setLikeBtn(post_key);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent singleBlogIntent = new Intent(MainActivity.this, BlogSingleActivity.class);
singleBlogIntent.putExtra("blog_id", post_key);
startActivity(singleBlogIntent);
}
});
mDatabaseUsers.child(model.getUid()).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imageUrl = dataSnapshot.getValue().toString();
viewHolder.setUserimage(getApplicationContext(), imageUrl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExist() {
final String user_id = this.mAuth.getCurrentUser().getUid();
this.mDatabaseUsers.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)) {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
MainActivity.this.startActivity(setupIntent);
}
if (user_id == null){Intent errorIntent = new Intent (MainActivity.this, ErrorActivity.class);
errorIntent.addFlags ( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(errorIntent);
MainActivity.this.startActivity (errorIntent);
}}
public void onCancelled(DatabaseError databaseError) {
}
});
}
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 setUserimage(Context context, String imageUrl) {
ImageView imageViewPostUserImage = (ImageView) mView.findViewById(R.id.imageview_post_userimage);
Glide
.with(context)
.load(imageUrl)
.into(imageViewPostUserImage);
}
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.mipmap.ic_thumb_up_black_24dp);
} else {
mLikeBtn.setImageResource(R.mipmap.ic_thumb_up_white_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setUsername(String username){
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, searchActivity.class);
searchIntent.putExtra("search", query);
startActivity(searchIntent);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//??????
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
searchActivity
public class searchActivity extends AppCompatActivity{
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private Query mQuery;
private Query mQuerySearch;
private SearchView mSearchView;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private boolean mProcessLike = false;
private TextView badge;
private String search;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent( com.fgvelectro.f.searchActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
search = getIntent().getExtras().getString("search");
mQuerySearch = mDatabase.orderByChild("title").equalTo(search);
mAuth.addAuthStateListener(mAuthListener);
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mQuery = mDatabase.orderByChild("title").equalTo("try1");
mBlogList = (RecyclerView) findViewById(R.id.blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
badge = (TextView)findViewById ( R.id.badge );
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog, searchActivity.BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
searchActivity.BlogViewHolder.class,
mQuerySearch
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
}
protected void populateViewHolder(final com.fgvelectro.f.MainActivity.BlogViewHolder viewHolder, Blog model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setLikeBtn(post_key);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent singleBlogIntent = new Intent( com.fgvelectro.f.searchActivity.this, BlogSingleActivity.class);
singleBlogIntent.putExtra("blog_id", post_key);
startActivity(singleBlogIntent);
}
});
mDatabaseUsers.child(model.getUid()).child("image").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imageUrl = dataSnapshot.getValue().toString();
viewHolder.setUserimage(getApplicationContext(), imageUrl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExist() {
final String user_id = this.mAuth.getCurrentUser().getUid();
this.mDatabaseUsers.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)) {
Intent setupIntent = new Intent( com.fgvelectro.f.searchActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
com.fgvelectro.f.searchActivity.this.startActivity(setupIntent);
}
if (user_id == null){Intent errorIntent = new Intent ( com.fgvelectro.f.searchActivity.this, ErrorActivity.class);
errorIntent.addFlags ( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity(errorIntent);
com.fgvelectro.f.searchActivity.this.startActivity (errorIntent);
}}
public void onCancelled(DatabaseError databaseError) {
}
});
}
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 setUserimage(Context context, String imageUrl) {
ImageView imageViewPostUserImage = (ImageView) mView.findViewById(R.id.imageview_post_userimage);
Glide
.with(context)
.load(imageUrl)
.into(imageViewPostUserImage);
}
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.mipmap.ic_thumb_up_black_24dp);
} else {
mLikeBtn.setImageResource(R.mipmap.ic_thumb_up_white_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setUsername(String username){
TextView post_username = (TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent( com.fgvelectro.f.searchActivity.this, searchActivity.class);
searchIntent.putExtra("search", query);
startActivity(searchIntent);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//??????
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent( com.fgvelectro.f.searchActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
Photo: Of the error
First, you need to query your database, example
mQuery = mDatabase.orderByChild("Title").equalTo("your value") then go to your firebaseRecyclerAdapter and replace:
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
)
with:
final FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mQuery
)
To find out more you can check the documentation here: https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query
and the FirebaseUI documentation: https://github.com/firebase/FirebaseUI-Android
This is what i did:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, searchActivity.class);
searchIntent.putExtra("search", query);
startActivity(searchIntent);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//??????
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
and in the search activity:
String search = getIntent().getExtras().getString("search");
mQuerySearch = mDatabase.orderByChild("name").equalTo(search);
FirebaseRecyclerAdapter<Classified, searchActivity.ClassifiedViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Classified, searchActivity.ClassifiedViewHolder>(
Classified.class,
R.layout.classified_row,
searchActivity.ClassifiedViewHolder.class,
mQuerySearch
)
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.