如何从Firebase子节点中检索时间戳,Android版。

huangapple go评论83阅读模式
英文:

How to retrieve time stamp from Firebase child Android

问题

以下是翻译好的内容:

我正在创建一个社交应用,当有人上传帖子时,上传帖子的时间也被记录下来。

我想要获取帖子上传的日期和时间,并以适当的形式展示给用户。例如,如果是在2小时前上传的,它将显示为"2小时前",而不是完整的上传日期和时间,或上传日期的时间戳。那么,我应该如何展示它,哪种方式最简单?

这段代码:

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

我得到了这个错误:

java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法'java.lang.String com.example.gone.Model.Post.getDate_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) {
            Post post = dataSnapshot.getValue(Post.class);
            dateAdded.setText(post.getDate_time());
        }

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

Post类:

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节点:

"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"
    },
    // 其他帖子的信息...
}
英文:

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 ?

如何从Firebase子节点中检索时间戳,Android版。

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

答案1

得分: 1

date_time不是Posts的直接子项。请将date_time替换为-MJ-VvX8zPdt2DY0pVqb

尝试如下:

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

更新

要显示所有帖子,您需要使用RecyclerView。

这里是从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);

更新 2

要显示时间:

// 如果date_time是Long类型,例如:1602557141467
val time = 1602557141467
// 如果date_time是String类型,例如: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")
}
英文:

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

Try like that:

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

Update:

To show all posts you need RecyclerView.

Here code that copied from Firebase Quickstart.

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

    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder&lt;Post&gt;()
            .setQuery(postsQuery, Post.class)
            .build();

    mAdapter = new FirebaseRecyclerAdapter&lt;Post, PostViewHolder&gt;(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(
        &quot;dd-MM-yyyy HH:mm:ss&quot;,
        Locale.getDefault()
    ).parse(&quot;01-10-2020 22:17:43&quot;)?.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(&quot;${days}d &quot;)
        if (hours != 0) append(&quot;${hours}h &quot;)
        if (minutes != 0) append(&quot;${minutes}m&quot;)
    }

答案2

得分: 0

我使用Gson来转换我的数据,在build.gradle中:

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

在我的代码中:

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

请记得让你的Post类实现Serializable接口,以在运行时获得更好的结果:

import java.io.Serializable;

public class Post implements Serializable{}

因为某种原因,直接在Firebase中进行操作会失败。

英文:

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

dependencies {
    implementation &#39;com.google.code.gson:gson:2.8.6&#39;
}

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

huangapple
  • 本文由 发表于 2020年10月14日 00:13:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64339099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定