【问题标题】:timestamp method 'SimpleDateFormat' not retrieving from database时间戳方法“SimpleDateFormat”未从数据库中检索
【发布时间】:2020-03-29 15:28:59
【问题描述】:

我遇到的问题是 timestamp 没有被保存,正如您在下面的 Firebase 中看到的那样。在Posts 下没有timestamp 孩子。有人可以向我解释这是为什么吗?

真的很感激有人看看并告诉我我做错了什么。

下面是timestamp 的代码。 PostAdapter.javaPostActivity.javaPost.java 模型类。

PostActivity.java


    package com.e.events;

    public class PostActivity extends AppCompatActivity {

        Uri imageUri;
        String myUrl = "";
        StorageTask uploadTask;
        StorageReference storageReference;

        ImageView close, post_checkmark, image_added;
        String description, text_event, text_location, text_date_time;
        EditText txt_event, txt_description, txt_location, txt_date_time;

        private String postId;
        private String postImage;
        private String publisher;
        private Map<String, String> timestamp;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_post);

            close = findViewById(R.id.close);
            post_checkmark = findViewById(R.id.post_checkmark);
            image_added = findViewById(R.id.new_image_added);
            txt_description = findViewById(R.id.description);
            txt_event = findViewById(R.id.text_event);
            txt_location = findViewById(R.id.text_location);
            txt_date_time = findViewById(R.id.text_date_time);

            storageReference = FirebaseStorage.getInstance().getReference("posts");

            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(PostActivity.this, MainActivity.class));
                    finish();
                }
            });

            post_checkmark.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    uploadImage();
                }
            });

            CropImage.activity()
                    .setAspectRatio(1, 1)
                    .start(PostActivity.this);
        }

    private void saveTimestamp() {
            Log.d(TAG, "saveTimestamp: getting timestamp");
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            String key = database.getReference().child("Posts").push().getKey();

            Post post = new Post(description, postId, postImage, publisher, timestamp, text_event, text_location, text_date_time);
            database.getReference("Posts").child(key).setValue(post);

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
            Map<String, Object> map = new HashMap<>();
            map.put("timestamp", ServerValue.TIMESTAMP);
            reference.child("Posts").setValue(map);
        }
    }

PostAdapter.java


    package com.e.events.Adapter;

    public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {

        public Context mContext;
        public List<Post> mPost;

        private FirebaseUser firebaseUser;

        public PostAdapter(Context mContext, List<Post> mPost) {
            this.mContext = mContext;
            this.mPost = mPost;
        }

        @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())) {
                Log.i(TAG, post.getTimestamp().toString());
                holder.timestamp.setVisibility(View.GONE);
            } else {
                holder.timestamp.setVisibility(View.VISIBLE);
                holder.timestamp.setText(post.getTimestamp().toString());
            }

    public class ViewHolder extends RecyclerView.ViewHolder {

            public TextView timestamp;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);


                timestamp = itemView.findViewById(R.id.timestamp);

            }

            //Set words for the timestamp "Today" or "___ days ago"
            private void setupWidgets() {
                String timestampDifference = getTimestampDifference();
                if (!timestampDifference.equals("0")) {
                    timestamp.setText(timestampDifference + " days ago");
                } else {
                    timestamp.setText("Today");
                }
            }

            //Timestamp
            private String getTimestampDifference() {
                Log.d(TAG, "getTimestampDifference: getting timestamp difference");

                String difference = "";
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy'T'HH:mm:ss'Z'", Locale.US);
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
                Date today = calendar.getTime();
                simpleDateFormat.format(today);
                Date timestamp;
                final String dateTime = simpleDateFormat.format(calendar.getTime());
                try {
                    timestamp = simpleDateFormat.parse(dateTime);
                    difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
                } catch (ParseException e) {
                    difference = "0";
                }
                return difference;
            }
        }

        private void getTimestamp() {
            DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    Long timestamp = (Long) snapshot.getValue();
                    System.out.println(timestamp);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

Post.java

package com.e.events.Model;

import android.widget.TextView;

import java.util.Map;

public class Post {

    private String postid;
    private String postimage;
    private String description;
    private String publisher;
    private String text_event;
    private String text_location;
    private String text_date_time;
    private Map<String, Object> timestamp;

    public Post(String postid, String postimage, String description, String publisher, String text_event, String text_location,
                String text_date_time, Map<String, Object> timestamp) {
        this.postid = postid;
        this.postimage = postimage;
        this.description = description;
        this.publisher = publisher;
        this.text_event = text_event;
        this.text_location = text_location;
        this.text_date_time = text_date_time;
        this.timestamp = timestamp;
    }

    public Post() {
    }

    public Post(String description, String postId, String postImage, String publisher, Map<String, String> textView, String text_event,
                String text_location, String timestamp) {
    }

    public String getPostid() {
        return postid;
    }

    public void setPostid(String postid) {
        this.postid = postid;
    }

    public String getPostimage() {
        return postimage;
    }

    public void setPostimage(String postimage) {
        this.postimage = postimage;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getText_event() {
        return text_event;
    }

    public void setText_event(String text_event) {
        this.text_event = text_event;
    }

    public String getText_location() {
        return text_location;
    }

    public void setText_location(String text_location) {
        this.text_location = text_location;
    }

    public String getText_date_time() {
        return text_date_time;
    }

    public void setText_date_time(String text_date_time) {
        this.text_date_time = text_date_time;
    }

    public Map<String, Object> getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Map<String, Object> timestamp) {
        this.timestamp = timestamp;
    }
}

【问题讨论】:

  • 在上面的代码中你正在检索
  • @PeterHaddad 我会尽可能清楚。我有一个PostActivity.java,它将您的照片上传到 Firebase。然后我有一个PostAdapter.java 和所有ViewHolders 等。我在PostAdapterPostActivity 中编写代码的位置是否重要?在 Firebase 中,是否应该像 postidpostimage 等一样为 timestamps 提供另一个节点?就像我说的,这是我第一次与timestamps 合作。
  • 我需要保存到 Firebase 并从 Firebase 中检索并将 timestamp 粘贴在 TextView 中。我不知道我离我有多远......

标签: java android firebase timestamp simpledateformat


【解决方案1】:

如果要为每个帖子添加timeStamp,则需要使用setValue()

FirebaseDatabase db = FirebaseDatabase.getInstance();
String key = db.getReference().child("Posts").push().getKey();

现在这将创建一个随机 ID,并将该 ID 存储在 key 变量中。

那么你可以这样做:

Posts post = new Post(description,postId,postImage,publisher,timestamp);
db.getReference("Posts").child(key).setValue(post);

updateChildren() 用于如果您想通过覆盖字段进行更新。但是您需要数据库中已经存在的推送 ID 才能在其下添加字段 timeStamp

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
                Map map = new HashMap();
                map.put("timestamp", ServerValue.TIMESTAMP);
                reference.child("Posts").child(key). updateChildren(map)

【讨论】:

  • 好吧,我改变了它,让它反映你上面的代码,但仍然没有timestamp。 Logcat 发出一条消息,上面写着 I/PlayCommon: [11594] ajzd.c(149): Connecting to server for timestamp: play.googleapis.com/play/log/timestamp ... 我写你的代码的方式有问题吗?
  • 添加以下内容:Map&lt;String, Object&gt; map = new HashMap&lt;&gt;()
  • 只需使用setValue,同样你添加那些字段添加时间戳也
  • 如果答案对您有帮助,请将其标记为正确并点赞,以便其他用户知道它有帮助,谢谢!
  • 兄弟,你介意我们在聊天中完成timestamp convo 吗?我想我很接近,只是Map&lt;String, Object&gt; 没有作为Post.java 类中的选项出现,只有Map&lt;String, String&gt;。你知道我该如何解决吗?我添加了一张图片,以便您可以看到我在说什么
猜你喜欢
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多