I am beginner at Android app development and I have created a chat app using Firebase database. I am using two Android phones to test the app, Android Samsung 4.4.2 API 19 and Samsung 5.0.1 API 21. The app used to work fine on both phones. I added some lines in the CharActivity for notification purpose, I ran the app, it worked fine on Android Samsung 4.4.2 API 19, but crashes on Samsung 5.0.1 API 21 at the lunch. So I undo all the changes I made until the point where my app was working fine on Samsung 5.0.1 API 21. But the surprise is it still crashes!
Now I am facing a problem with the Samsung 5.0.1 API 21. Every time I run the app it crashes at the lunch, and here is the problem I get.
FATAL EXCEPTION: main
Process: com.example.maalialabdulhafith.nfc_mac, PID: 30357
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Please note that my other Android Samsung 4.4.2 API 19 works fine and doesn't crash.
FriendsFragment Class (Where all my friends are listed)
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
#Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
//friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
final String userStatus = dataSnapshot.child("status").getValue().toString(); // I added this
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserStatus(userStatus); //<== if you want to show status instead of date
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
/*public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}*/
//if you want to display the statuse instead of the date, activite this and comment setDate method
public void setUserStatus(String status) {
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
Chat Class
public class ChatActivity extends AppCompatActivity {
// user id whom we want to chat with
private String mChatUser;
private DatabaseReference mRootRef;
private TextView mTitleView;
private TextView mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMessageView;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout; // For Pagination
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
// For Pagination
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos = 0;
private String mLastKey = "";
private String mPrevKey = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat2);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mChatUser = getIntent().getStringExtra("user_id");
String userName = getIntent().getStringExtra("user_name");
getSupportActionBar().setTitle(userName);
// to display the image in the bar
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
// ---- Custom Action bar Items ----
mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mLastSeenView = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(custom_bar_image);
//mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mAdapter = new MessageAdapter(messagesList);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout); // pagenation
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
// showing last time was seen
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
if(online.equals("true")) {
mLastSeenView.setText("Online");
} else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
}
//CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.custom_bar_image);
//Picasso.with(i).load(image).placeholder(R.drawable.default_avatar).into(userImageView);
//Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen", false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/" + mCurrentUserId + "/" + mChatUser, chatAddMap);
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
// Swipe/Pull to Refresh for Android RecyclerView
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mCurrentPage++;
itemPos = 0;
loadMoreMessages();
}
});
}
// ------------------ LOAD More Messages ------------------
private void loadMoreMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
} else{
mPrevKey=mLastKey;
}
if (itemPos == 1){
mLastKey = messageKey;
}
Log.d("TOTALKEYS", "Last Key: " + mLastKey + "| Prev Key: " + mPrevKey + "| Message Key: " + messageKey );
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(10,0);
}
#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) {
}
});
}
// ------------------ LOAD Messages ------------------
private void loadMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if (itemPos == 1){
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(messagesList.size () -1);
mRefreshLayout.setRefreshing(false);
}
#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) {
}
});
}
private void sendMessage() {
String message = mChatMessageView.getText().toString();
if(!TextUtils.isEmpty(message)){
String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
String push_id = user_message_push.getKey();
Map messageMap = new HashMap();
messageMap.put("message", message);
messageMap.put("seen", false);
messageMap.put("type", "text");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
}
What doesn't make sense to me is, how does it run on one device and doesn't on other? I would appreciate a detailed answer. Thanks in advance!
Acknowledgment: I have learned this code from the amazing TVAC Studio on Youtube.
The user is not signed-in.
Change your code to the following
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null && !firebaseUser.getUid().isEmpty()) {
// all OK
} else {
// repeat the authentication process again
}
As explained by tim4dev, you havent logged in using any specific user. If you havent created a user, go to the firebase console and allow a signup type. They are like email and password auth, phone number auth, anonymous, etc. Once you have enabled one of the options, you can sign up using the auth class and sign in / login afterwards. Once you login with a user account on a device, only then will the
mCurrent_user_id = mAuth.getCurrentUser().getUid();
statement work and return a non-null id.
Hope it solves the problem.
Related
So basically I have implemented a fragment for my app using firebase Recycler Adapter. I have searched through out the internet to hide a row in the recycler view without occupying white space. I have applied various people solutions but result is same.
My Fragment code is like this:
public class RequestFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_request, container, false);
mReqList = (RecyclerView) mMainView.findViewById(R.id.req_list);
mRootRef =FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser() !=null)
mCurrent_user_id = mAuth.getCurrentUser().getUid();
if(mCurrent_user_id !=null) {
mReqDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req").child(mCurrent_user_id);
mReqDatabase.keepSynced(true);
}
text = (TextView) mMainView.findViewById(R.id.request_fragment_text);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mReqList.setHasFixedSize(true);
mReqList.setLayoutManager(linearLayoutManager);
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
if(mReqDatabase != null) {
final Query requestQuery = mReqDatabase.orderByChild("request_type");
FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder> firebaseReqAdapter = new FirebaseRecyclerAdapter<Request, RequestFragment.ReqViewHolder>(
Request.class,
R.layout.single_request_layout,
ReqViewHolder.class,
requestQuery
) {
#Override
protected void onDataChanged() {
if(getItemCount() == 0){
text.setText("No New Friend Request");
}
else{
text.setText("");
}
}
#Override
protected void populateViewHolder(final RequestFragment.ReqViewHolder reqViewHolder, final Request req, int i) {
final String list_user_id = getRef(i).getKey();
mAcceptBtn = reqViewHolder.mView.findViewById(R.id.single_req_accept_btn2);
mDeclineBtn = reqViewHolder.mView.findViewById(R.id.single_req_decline_btn);
if (req.getRequest_type().equals("received")) {
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
text.setText("");
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
reqViewHolder.setUserOnline(userOnline);
}
reqViewHolder.setName(userName);
reqViewHolder.setUserImage(userThumb, getContext());
mAcceptBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friends/" + mCurrent_user_id + "/" + list_user_id + "/date", currentDate);
friendsMap.put("Friends/" + list_user_id + "/" + mCurrent_user_id + "/date", currentDate);
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
mDeclineBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
Map friendsMap = new HashMap();
friendsMap.put("Friend_req/" + mCurrent_user_id + "/" + list_user_id, null);
friendsMap.put("Friend_req/" + list_user_id + "/" + mCurrent_user_id, null);
mRootRef.updateChildren(friendsMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
reqViewHolder.mView.setVisibility(View.INVISIBLE);
} else {
String error = databaseError.getMessage();
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
reqViewHolder.Invisible();
text.setText("No New Friend Request");
}
}
};
mReqList.setAdapter(firebaseReqAdapter);
}
}
public static class ReqViewHolder extends RecyclerView.ViewHolder {
View mView;
public ReqViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setStatus(String status) {
TextView fragmentStatus = mView.findViewById(R.id.request_fragment_text);
fragmentStatus.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.req_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.req_single_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.req_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
public void Invisible(){
mView.setVisibility(View.INVISIBLE);
}
}
}
My fragment in the app is looking like this:
Can anyone help me how to get rid of this white space?
This is my firebase storage image and I want to display all images from url into gridview by taking the current user id
This is my main activity onstart() that leads to adapter class.
I want to show all the images under current user id like grid view.
How to display all user image posts in grid view from firebase above image.
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
uploads = new ArrayList<Blog>();
if (currentUser != null && !currentUser.isAnonymous()) {
mUserf.child("online").setValue("true");
mProgressbar.setMessage("Welcome.....");
mProgressbar.show();
mProgressbar.dismiss();
ConnectivityManager check = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = check.getActiveNetworkInfo(); //for checking whether app is connected to a network or not..
if(info!=null && info.isConnected()) {
//Toast.makeText(MainActivity.this, "network available", Toast.LENGTH_SHORT).show();
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching Blogs.....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
alpha = FirebaseDatabase.getInstance().getReference().child("Blog").child(mAuth.getCurrentUser().getUid());
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
} else {
//Toast.makeText(MainActivity.this, "No network available", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
// mDatabseUsers.child("online").setValue("true");
} else {
Intent user1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(user1);
}
}
This is my adapter class where
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.myviewholder> {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
//List<String> imageUrls ;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);//this view will contain appearance of each layout i.e each row..
myviewholder holder=new myviewholder(v);// we are passing the view of each row to the myviewholder class
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {//here we will inflate datas in the widgets i.e image and title..
//It is called for each row..so every row is inflated here..
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
/*int count = 0;
for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
count += images.size();
}*/
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
Picasso.with(context).load(imageUrls.get(position)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(position));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
// It contains the elements in each row that we will inflate in the recyclerView..
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);//here we link with the elements of each view i.e each row and
// desc = (TextView) itemView.findViewById(R.id.postdesc);//here we link with the elements of each view i.e each row and
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
//here we link with the elements of each view i.e each row and
// likebtn = (ImageButton)itemView.findViewById(R.id.likebtn);
// viewbtn = (ImageButton)itemView.findViewById(R.id.viewbtn);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mprogressview = true;
int pos = getAdapterPosition();
Blog b = list.get(pos);
Intent intent = new Intent(context,CommentBox.class);
Bundle bundle = new Bundle();
bundle.putString("post_key",b.getUid().toString());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
over = (ImageView) itemView.findViewById(R.id.overflow);
over.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFilterPopup(v);
}
});
});
itemView.setOnClickListener(this);
}
}
To display all those url's, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference urlRef = rootRef.child("Blog").child(uid).child("url");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
urlRef.addListenerForSingleValueEvent(valueEventListener);
And here is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.
Edit:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Blog").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uid = dataSnapshot.child("uid").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String timestamp = dataSnapshot.child("timestamp").getValue(String.class);
Log.d("TAG", uid + " / " + title + " / " + timestamp);
for(DataSnapshot ds : dataSnapshot.child("url").getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
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
There is my activity:
public class EventDetailsActivity extends AppCompatActivity {
private Event event;
private ArrayList<User> subscribedUsers;
private RecyclerView mRecyclerView;
private String eventId;
private SubscribedUsersAdapter adapter;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
context = this;
Bundle extras = getIntent().getExtras();
eventId = extras.getString("eventId");
setUpEvent();
}
private void setUpEvent() {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(eventId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventType = dataSnapshot.child("eventType").getValue().toString();
String description = dataSnapshot.child("description").getValue().toString();
Object object = dataSnapshot.child("startingDate").getValue();
HashMap result = (HashMap) object;
int year = Integer.parseInt(result.get("year").toString());
int month = Integer.parseInt(result.get("month").toString());
int day = Integer.parseInt(result.get("date").toString());
int hour = Integer.parseInt(result.get("hours").toString());
int minute = Integer.parseInt(result.get("minutes").toString());
Date startingDate = new Date(year,month,day,hour,minute,0);
object = dataSnapshot.child("location").getValue();
result = (HashMap) object;
double latitude = Double.parseDouble(result.get("latitude").toString());
double longitude = Double.parseDouble(result.get("longitude").toString());
LatLng location = new LatLng(latitude,longitude);
String userId = dataSnapshot.child("userId").getValue().toString();
String userName = dataSnapshot.child("userName").getValue().toString();
String userPicture = dataSnapshot.child("userPicture").getValue().toString();
subscribedUsers = new ArrayList<User>();
if (dataSnapshot.hasChild("subscribedUsers")) {
mDatabase.child("subscribedUsers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
event = new Event(eventId, eventType,description,startingDate,location,userId, userName, userPicture);
setText();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setText()
{
ImageView mProfilePicture = (ImageView) findViewById(R.id.profilePicture);
if (!EventDetailsActivity.this.isFinishing()) {
Glide
.with(this)
.load(event.getUserPicture())
.into(mProfilePicture);
}
TextView mUserName = (TextView) findViewById(R.id.userName);
mUserName.setText(event.getUserName());
TextView mEventType = (TextView) findViewById(R.id.eventType);
mEventType.setText(event.getEventType());
TextView mDescription = (TextView) findViewById(R.id.description);
mDescription.setText(event.getDescription());
if (!EventDetailsActivity.this.isFinishing()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(new OnMapReadyCallback()
{
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.clear();
googleMap.addMarker(new MarkerOptions().position(event.getLocation()));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(event.getLocation(),12.0f));
}
});
}
TextView mStartingDate = (TextView) findViewById(R.id.startingDate);
Date startingDate = event.getStartingDate();
String displayText = String.valueOf(startingDate.getYear());
int month = startingDate.getMonth() + 1;
if (month/10 == 0)
{
displayText = displayText + ".0" + month;
}
else
{
displayText = displayText + "." + month;
}
if (startingDate.getDate()/10 == 0)
{
displayText = displayText + ".0" + startingDate.getDate();
}
else
{
displayText = displayText + "." + startingDate.getDate();
}
if (startingDate.getHours()/10 == 0)
{
displayText = displayText + ". 0" + startingDate.getHours();
}
else
{
displayText = displayText + ". " + startingDate.getHours();
}
if (startingDate.getMinutes()/10 == 0)
{
displayText = displayText + ":0" + startingDate.getMinutes();
}
else
{
displayText = displayText + ":" + startingDate.getMinutes();
}
mStartingDate.setText(displayText);
setUpRecyclerView();
subscribe();
}
private void setUpRecyclerView() {
adapter = new SubscribedUsersAdapter(this,subscribedUsers);
mRecyclerView.setAdapter(adapter);
}
private void subscribe()
{
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
final String userId = mAuth.getCurrentUser().getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("name").getValue().toString();
String userPicture = dataSnapshot.child("picture").getValue().toString();
User user = new User(userId, userName, userPicture);
userSubscribe(user);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
userSubscribe(null);
}
}
private void userSubscribe(final User user) {
Button mSubscribeButton = (Button) findViewById(R.id.subscribeButton);
if (user == null)
{
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(EventDetailsActivity.this, getResources().getString(R.string.logInToSubscribe), Toast.LENGTH_LONG).show();
Intent loginIntent = new Intent(EventDetailsActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
});
}
else if (containsUser(subscribedUsers,user) == -1)
{
mSubscribeButton.setText(getResources().getString(R.string.subscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
subscribedUsers.add(user);
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
else
{
mSubscribeButton.setText(getResources().getString(R.string.unsubscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
int position = containsUser(subscribedUsers,user);
subscribedUsers.remove(position);
mDatabase.child("subscribedUsers").removeValue();
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
private int containsUser(ArrayList<User> users, User user)
{
for (int i=0; i<users.size(); ++i)
{
if (users.get(i).getUserId().equals(user.getUserId()))
{
return i;
}
}
return -1;
}
}
And my adapter:
public class SubscribedUsersAdapter extends RecyclerView.Adapter<SubscribedUsersAdapter.ViewHolder>{
private Context context;
private ArrayList<User> items;
public SubscribedUsersAdapter(Context context, ArrayList<User> items) {
this.context = context;
this.items = items;
}
protected static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mProfilePictureView;
public TextView mUserName;
public ViewHolder(View itemView) {
super(itemView);
mProfilePictureView = (ImageView) itemView.findViewById(R.id.profilePictureView);
mUserName = (TextView) itemView.findViewById(R.id.userName);
}
}
#Override
public SubscribedUsersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final User item = items.get(position);
Glide
.with(context)
.load(item.getPicture())
.into(holder.mProfilePictureView);
holder.mUserName.setText(item.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(context, ProfileActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
profileIntent.putExtra("userId", item.getUserId());
context.startActivity(profileIntent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
}
When the activity starts firstly, the data is displayed well in RecyclerView, but if a user subscribes to the event or unsubscribe from it, the RecyclerView will be empty.
I tried with notifyDataSetChanged, notifyItemRangeInserted, notifyItemRangeRemoved, but none of them worked or I didn't use it well. I don't know.
Thanks for your help!
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
after that just add this line
adapter.notifyDataSetChanged();
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.