java - Android studio Firestore 两个 Activity 之间的时间戳错误

标签 java android firebase google-cloud-firestore

suggest collection users collection我有一个简单的建议页面,我可以在其中输入标题和内容,然后将一些其他信息存储到 Firestore,并在 ListView 页面上显示它。它本身工作正常,但是在我发送它之后,弹出一个错误,它显示错误是 ListView 页面上的时间戳 toDate

Activity 顺序为listview>发送页面>listview。

//the send activity
 send.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               v.getId();
               String title = art1.getText().toString();
               String content = art2.getText().toString();


               Intent intent = new Intent(create_announce_main.this, SuggestionMain.class);

               //  DocumentReference documentReference = firebaseFirestore.collection("announce").document("ann");
               Map<String, Object> suggest = new HashMap<>();
               suggest.put("title", title);
               suggest.put("content", content);
               suggest.put("name", name);
               suggest.put("recID", recID);
               suggest.put("admin_name", "");
               suggest.put("response_content", "");
               suggest.put("response_status", "未回覆");
               suggest.put("response_time",FieldValue.serverTimestamp());
               suggest.put("createdAt", FieldValue.serverTimestamp());
               firebaseFirestore.collection("Suggestion").document().set(suggest).addOnCompleteListener(new OnCompleteListener<Void>() {
                   @Override
                   public void onComplete(@NonNull Task<Void> task) {
                       if (task.isSuccessful()) {
                           Toast.makeText(create_announce_main.this, "added succesfully", Toast.LENGTH_LONG).show();


                       }
                   }
               });

               startActivity(intent);


           }
       }); 

到 ListView 页面

//the view
DocumentReference docRef = firebaseFirestore.collection("users").document(userID);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Log.d("TAG", "DocumentSnapshot data: " + document.getData());
                        recID = document.getString("recID");
                        firebaseFirestore.collection("Suggestion").whereEqualTo("recID",recID).orderBy("createdAt", Query.Direction.DESCENDING).addSnapshotListener((documentSnapshots, error) -> {
                            ar.clear();

                            for (DocumentSnapshot snapshot : documentSnapshots){
                                idlv = snapshot.getId();
                                Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");

                             **Date date = timestamp.toDate();//the error is at here**
                                String date2 = date.toString();

                                ar.add(new itemAnnounce(R.drawable.notes, snapshot.getString("title"),"回饋於 "+date2,"回覆管理者:"+snapshot.getString("admin_name"),"回覆狀態:"+snapshot.getString("response_status"),idlv,url));


                            }
                            adapterAnnounce adapterAnnounce = new adapterAnnounce(getApplicationContext(), R.layout.list_row_announce, ar);
                            adapterAnnounce.notifyDataSetChanged();
                            lv1.setAdapter(adapterAnnounce);

                            lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Object selectedObj =adapterAnnounce.getItem(position).getId();// this will get you selected obj of itemAnnounce
                                    String obj = (String)selectedObj.toString();

                                    Intent i = new Intent(SuggestionMain.this, announce_Page.class);
                                    i.putExtra("annId",obj);
                                    startActivity(i);
                                }
                            });
                        });
                    } else {
                        Log.d("TAG", "No such document");
                    }
                } else {
                    Log.d("TAG", "get failed with ", task.getException());
                }
            }
        });

弹出错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.districtapp, PID: 12764
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date com.google.firebase.Timestamp.toDate()' on a null object reference
        at com.example.districtapp.SuggestionMain$1.lambda$onComplete$0$SuggestionMain$1(SuggestionMain.java:65)
        at com.example.districtapp.-$$Lambda$SuggestionMain$1$70rkZQjkWJS7wHwVoKS2O7TV5ls.onEvent(Unknown Source:4)
        at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2(Query.java:1133)
        at com.google.firebase.firestore.Query$$Lambda$3.onEvent(Unknown Source:6)
        at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
        at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

当我第一次触摸firestore时,我对这种事情有印象,所以我尝试首先启动发送 Activity 而不是 View ,它有效,但只是一次,第二次它显示相同的错误,我尝试过当 onclick 发送页面时完成整个 Activity ListView ,仍然不起作用,

Firestore 正在完美获取数据,并且重新启动应用程序后,listview 显示数据,因此该功能正在运行。 suggest field

最佳答案

由于以下代码行,您将收到 NullPointerException:

Date date = timestamp.toDate();

这是因为 timestamp 对象位于:

Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");

值为空。要解决这个问题,请将上面的代码行更改为:

if (snapshot.getDate("createdAt") != null) {
    Date timestamp = snapshot.getDate("createdAt");
    //Do what you need to do with this timestamp
}

除此之外,还有这样的查询:

firebaseFirestore.collection("Suggestion").whereEqualTo("recID",recID).orderBy("createdAt", Query.Direction.DESCENDING)

需要一个索引。要添加这样的索引,请检查我在以下帖子中的回答:

关于java - Android studio Firestore 两个 Activity 之间的时间戳错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67906104/

相关文章:

java - 在 BufferedReader 中获取 read() 返回的字符

java - FlyWay 版本

java - 在多模块 Java/scala 项目中有一个通用的 webapp?

Java 和 OpenAPI - 根据响应代码返回不同的负载

android - 从父 Activity 中的子 Activity 中捕获异常

android - 如何使用代码在 SlidingDrawer 中添加 TextView?

android - 解析,添加关系。无法对与未保存的 ParseObject 的关联进行编码

javascript - 将对象添加到 Firebase 时设置自己的 key - AngularFire

ios - 将庞大的 Firebase 数据库作为事务更新

node.js - 带查询的 firebase 函数中的循环