【问题标题】:Firebase timestamp doesn't retrieve timestamp in SimpleDateFormatFirebase 时间戳不检索 SimpleDateFormat 中的时间戳
【发布时间】:2020-04-08 10:07:37
【问题描述】:

多年来一直致力于此timestamp,并使用 StackOverflow 的大量帖子来帮助我完成它。终于将timestamp 与所有其他孩子一起保存在 Firebase 中以获取图片,但我无法让它出现在 TextView 中的应用程序中。

所以在我的PostActivity.java 类中,我使用Maptimestamp 保存到Firebase,然后在我的PostAdapter.java 类中我有ViewHolders,因此它出现在我的RecyclerViewHomeFragment,但它以 Long41526276373 的形式出现,而不是应有的 SimpleDateFormat

有人可以帮我吗?

下面有我的PostActivity.java 类和PostAdapter.java 类。

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 已更新

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

【问题讨论】:

  • 顺便考虑扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友,并将ThreeTenABP添加到您的Android项目中,以便使用java.time,现代Java日期和时间API .使用起来感觉好多了。

标签: java android firebase firebase-realtime-database timestamp


【解决方案1】:

写完下面的答案后,我突然注意到你似乎没有从视图持有者的任何地方调用你的 getTimeDate 辅助方法,这可以解释为什么时间戳显示为一个数字。


当您在 Firebase 实时数据库中保存 ServerValue.TIMESTAMP 时,它会存储一个值,该值计算自纪元以来经过的毫秒数。所以这确实是一个数值(而且相当大)。

要将其显示为日期,请将其传递给new Date(...)

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

在许多情况下,我看到开发人员在他们的 POJO Java 类中添加了一个方便的方法,例如您的案例中的 Post 类。比如:

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);
        }
    }

}

然后在你的视图持有者中使用它:

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

另见:

【讨论】:

  • 嘿伙计,谢谢你的解释。让我离最终目标更近了。你能解释一下你上面写的getTimeDate方法的最后一部分吗?我不明白return new RuntimeException(e); 部分......此外,它以红色下划线的代码返回。不应该是String吗?如果你能解释一下,我可以更好地理解它
  • 该死.. 我有一段时间没有在 Java 中进行日期操作了,所以应该知道得更好。我刚刚注意到您的代码吞下了异常,您可能想要重新抛出它。随意以其他方式显示它,例如记录它。
  • 带 *** 的行仍然是错误的,我不知道为什么。我改变了方法来抛出我认为的异常。我用 PostAdapter.java Updated 更新了文本
  • 如果您在改进错误处理时遇到问题,请随时保留您所拥有的。这只是一个小的(预期的)改进,与您的实际问题无关。
  • holder.timestamp.setText(new Date(post.getTimestamp())); 是正确的,但考虑到我想更改日期格式,第二个对我来说是更好的选择,这就是为什么我试图弄清楚为什么更改的代码行红色下划线
猜你喜欢
  • 2022-11-20
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2015-07-27
  • 2013-06-20
相关资源
最近更新 更多