neko12
neko12

Reputation: 33

Android studio Firestore timestamp error between two acitivity

suggest collectionusers collectionI have a simple suggestion page where I can type title and contents, then store some other information to the Firestore, show it on ListView pages. It works fine itself, but after I send it, an error pops and it shows the bug is the timestamp toDate on the listview pages

The order of activities is listview>sending page>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);


           }
       }); 

to listview page

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

the error pops

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)

I have impression about this sort of thing when I touch firestore the first time,So i tried to start the send activity first not the view,it works out but just for once,second time it shows the same bug,I tried to finish the whole activity listview when onclick to sendpage,still dont work,

Firestore is getting the data perfectly, and after restarting the app, listview shows the data, so the function is working though. suggest field

Upvotes: 2

Views: 202

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

You are getting NullPointerException because of the following line of code:

Date date = timestamp.toDate();

And this is because the timestamp object in:

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

Has the value of null. To solve this, please change the above line of code to:

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

Besides that, a query like this:

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

Requires an index. To add such an index please check my answer from the following post:

Upvotes: 2

Related Questions