简体   繁体   中英

How to retrieve time stamp from Firebase child Android

I am creating a social app and when someone uploads a post the time they uploaded the post is also uploaded.

I want to get the date and time it was uploaded and show it to the user in a proper form. For example if it was uploaded 2 hours ago it will say 2hr instead of the entire date and time it was uploaded or the time stamp of the uploaded date. So how do I show it and which was is easiest ?

我如何在我的数据库中节省时间

This code:

Post post = dataSnapshot.getValue(Post.class);
dateAdded.setText(post.getDate_time());

I get this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.gone.Model.Post.getDate_time()' on a null object reference

So if someone has a way of doing this can someone please help me ? Thanks

EDIT ---

The method where I want to show the date/time -

private void getDate(TextView dateAdded) {

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Posts").child("date_time");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            //dateAdded.setText((CharSequence) dataSnapshot.child("date_time"));
            Post post = dataSnapshot.getValue(Post.class);
            dateAdded.setText(post.getDate_time());
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

Post.class:

private String date_time;

public String getDate_time() {
    return date_time;
}

public void setDate_time(String date_time) {
    this.date_time = date_time;
}

public Post(String date_time) {
    this.date_time = date_time;
}

JSON node:

    "Posts" : {
    "-MJ-VvX8zPdt2DY0pVqb" : {
      "date_time" : "01-10-2020 22:17:43",
      "description" : "",
      "postid" : "-MJ-VvX8zPdt2DY0pVqb",
      "postimage" : "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/posts%2F1602031430356.null?alt=media&token=dc7c4a5c-d652-44be-bb2a-28283964da1e",
      "publisher" : "gIt685Xex8eZaPBSsbcPbU1S5V93"
    },
    "-MJ-qP4mKkkXCTGQeqhq" : {
      "date_time" : "06-10-2020 22:17:43",
      "description" : "",
      "postid" : "-MJ-qP4mKkkXCTGQeqhq",
      "postimage" : "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/posts%2F1602037062255.null?alt=media&token=5fde471b-f794-4376-8250-18c0893c716e",
      "publisher" : "gIt685Xex8eZaPBSsbcPbU1S5V93"
    },
    "-MJUqKzwnZfC0cVRRohI" : {
      "dateAdded" : "12-10-2020 22:45:41",
      "date_time" : "1602557141467",
      "description" : "",
      "postid" : "-MJUqKzwnZfC0cVRRohI",
      "postimage" : "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/posts%2F1602557139321.null?alt=media&token=06af1115-481a-4c0f-8ba7-3bef13da3989",
      "publisher" : "J51XZDETvNT86eCLtqU5XHUzEWu2"
    }
  }

date_time is not direct child of Posts . Instead of date_time paste -MJ-VvX8zPdt2DY0pVqb .

Try like that:

DatabaseReference reference = FirebaseDatabase
    .getInstance()
    .getReference()
    .child("Posts")
    .child("-MJ-VvX8zPdt2DY0pVqb");

Update :

To show all posts you need RecyclerView.

Here code that copied from Firebase Quickstart .

    Query postsQuery = FirebaseDatabase
        .getInstance().getReference().child("Posts").limitToFirst(100);

    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Post>()
            .setQuery(postsQuery, Post.class)
            .build();

    mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {

        @Override
        public PostViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
            return new PostViewHolder(inflater.inflate(R.layout.item_post, viewGroup, false));
        }

        @Override
        protected void onBindViewHolder(PostViewHolder viewHolder, int position, final Post model) {
            // model.date
            });
        }
    };
    mRecycler.setAdapter(mAdapter);

Update 2:

To show time:

    // if date_time is Long like: 1602557141467
    val time = 1602557141467
    // if date_time is String like: 01-10-2020 22:17:43
    val time = SimpleDateFormat(
        "dd-MM-yyyy HH:mm:ss",
        Locale.getDefault()
    ).parse("01-10-2020 22:17:43")?.time ?: 0

    val deltaTime = Date().time - time

    val minutes = (deltaTime / (60 * 1000)).toInt() % 60
    val hours = (deltaTime / ( 60 * 60 * 1000)).toInt() % 24
    val days = (deltaTime / ( 24 * 60 * 60 * 1000)).toInt()


    val result = buildString {
        if (days != 0) append("${days}d ")
        if (hours != 0) append("${hours}h ")
        if (minutes != 0) append("${minutes}m")
    }

I use Gson for convert my data, in build.gradle:

dependencies {
    implementation 'com.google.code.gson:gson:2.8.6'
}

In my code:

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(dataSnapshot.getValue());
Post post = gson.fromJson(jsonElement, Post.class);
dateAdded.setText(post.getDate_time());

Remember make your Post class Serializable to have better results in runtime

import java.io.Serializable;
public class Post implements Serializable{}

For some reason doing it direct with Firebase fails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM