0

Been working on this timestamp for ages and using numerous posts from StackOverflow to help me through it. Finally got timestamp saving in Firebase along with all the other children for the pictures, but I can't get it to come upon the app in the TextView.

So in my PostActivity.java class I have used Map to save the timestamp to Firebase, and then in my PostAdapter.java class I have the ViewHolders so that it appears in the RecyclerView in my HomeFragment, but it's coming out as a Long value 41526276373and not in SimpleDateFormat as it should.

Can someone help me?

Below you have my PostActivity.java class and PostAdapter.java class.

PostActivity.java

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");

                        String postid = reference.push().getKey();

                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("postid", postid);
                        hashMap.put("postimage", myUrl);
                        hashMap.put("description", txt_description.getText().toString());
                        hashMap.put("text_event", txt_event.getText().toString());
                        hashMap.put("text_location", txt_location.getText().toString());
                        hashMap.put("text_date_time", txt_date_time.getText().toString());
                        hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
                        hashMap.put("timestamp", ServerValue.TIMESTAMP);

                        reference.child(postid).setValue(hashMap);

                        //Do I have to put here reference.updateChildren(hashmap)?

                        progressDialog.dismiss();

                        startActivity(new Intent(PostActivity.this, MainActivity.class));
                        finish();
                    } else {
                        Toast.makeText(PostActivity.this, "Unsuccessful. Try again", Toast.LENGTH_SHORT).show();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(PostActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
        }
    }

    public static String getTimeDate(long timestamp) {
        try {
            DateFormat dateFormat = DateFormat.getDateTimeInstance();
            Date netDate = (new Date(timestamp));
            return dateFormat.format(netDate);
        } catch (Exception e){
            return "timestamp";
        }
    }

PostAdapter.java

 @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, parent, false);
        return new PostAdapter.ViewHolder(view);

    }
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    final Post post = mPost.get(position);

    Glide.with(mContext).load(post.getPostimage())
            .apply(new RequestOptions().placeholder(R.drawable.placeholderimg))
            .into(holder.post_image);

    if ("".equals(post.getTimestamp())) {
        holder.timestamp.setVisibility(View.GONE);
    } else {
        if (post.getPostid() != null) {
            holder.timestamp.setVisibility(View.VISIBLE);
            holder.timestamp.setText(post.getTimestamp().toString());
        }
    }

PostAdapter.java Updated

if ("".equals(post.getTimestamp())) {
            holder.timestamp.setVisibility(View.GONE);
        } else {
            if (post.getPostid() != null) {
                holder.timestamp.setVisibility(View.VISIBLE);
               ***holder.timestamp.setText(post.getTimeDate());***
            }
        }

***getTimeDate(post.getPostid(), holder.timestamp);***

public String getTimeDate(long timestamp) {
        try {
            DateFormat dateFormat = DateFormat.getDateTimeInstance();
            Date netDate = (new Date(this.timestamp));
            return dateFormat.format(netDate);
        } catch (Exception e) {
            throw e;
        }
    }
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 16 '19 at 13:56

1 Answers1

2

After writing the below answer, I suddenly noticed you don't seem to be calling your getTimeDate helper method from anywhere in the view holder, which would explain why the timestamp shows up as a number.


When you save a ServerValue.TIMESTAMP in Firebase Realtime Database, it stores a value that counts the number of milliseconds that have passed since the epoch. So this is indeed a numerical (and rather large) value.

To show it as a date, pass it into new Date(...):

holder.timestamp.setText(new Date(post.getTimestamp()));

In many cases I've seen developers add a convenience method to their POJO Java class, such as the Post class in your case. Something like:

class Post .... {
    ...

    public String getTimeDate(long timestamp) {
        try {
            DateFormat dateFormat = DateFormat.getDateTimeInstance();
            Date netDate = (new Date(this.timestamp));
            return dateFormat.format(netDate);
        } catch (Exception e){
            return new RuntimeException(e);
        }
    }

}

And then use that in your view holder as:

holder.timestamp.setText(post.getTimeDate());

Also see:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hey man, thanks for the explanation. Has brought me a lot closer to my end goal. Could you please explain the last part of the ```getTimeDate``` method that you wrote above? I don't understand the ```return new RuntimeException(e);``` part... Also, it comes back underlined in red the code. Shouldn't it be a ```String```? If you could explain it so I can understand it better – johnnnnyyyy Dec 16 '19 at 13:57
  • Darn.. I haven't done date manipulation in Java in a while, so should've known better. I just noticed that your code swallowed the exception, and you'll probably want to instead rethrow it. Feel free to surface it in another way, such as logging it. – Frank van Puffelen Dec 16 '19 at 16:08
  • The lines with *** are still wrong and I don't know why. I changed the method to throw the exception I think. I updated the text with ***PostAdapter.java Updated*** – johnnnnyyyy Dec 16 '19 at 17:59
  • If you're having trouble improving the error handling, feel free to leave what you had. It was just a minor (intended) improvement and not related to your actual problem. – Frank van Puffelen Dec 16 '19 at 18:21
  • The ```holder.timestamp.setText(new Date(post.getTimestamp()));``` was spot on, but the second one is the better option for me considering I want to change the date format, this is why I am trying to figure out why the changed lines of code are being underlined in red – johnnnnyyyy Dec 16 '19 at 19:00