简体   繁体   English

时间戳方法“SimpleDateFormat”不从数据库中检索

[英]timestamp method 'SimpleDateFormat' not retrieving from database

The problem which I am having is that the timestamp isn't being saved as you can see below in Firebase.我遇到的问题是timestamp没有被保存,如下面的 Firebase 所示。 Under Posts no timestamp child.Posts没有timestamp子项。 Can someone explain to me why that is?有人可以向我解释这是为什么吗?

Really would appreciate someone taking a look and telling me what I'm doing wrong.真的很感激有人看一眼并告诉我我做错了什么。

Below you have the code for the timestamp .下面是timestamp的代码。 PostAdapter.java , PostActivity.java , and Post.java Model class. PostAdapter.javaPostActivity.javaPost.java模型类。

在此处输入图片说明

PostActivity.java发布活动.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后适配器.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后.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;
    }
}

If you want to add timeStamp for each post, then you need to use setValue() :如果要为每个帖子添加timeStamp ,则需要使用setValue()

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

Now this will create a random ID and you will store the id inside the key variable.现在这将创建一个随机 ID,并将该 ID 存储在key变量中。

Then you can do:然后你可以这样做:

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

updateChildren() is used if you want to update with overwriting the fields.如果您想通过覆盖字段进行更新,则使用updateChildren() But you need the push ID that is already in your database to be able to add the field timeStamp under it:但是您需要数据库中已有的推送 ID timeStamp在其下添加字段timeStamp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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