java - 两个活动之间的Android Studio Firestore时间戳错误
问题描述
建议集合用户集合我有一个简单的建议页面,我可以在其中键入标题和内容,然后将一些其他信息存储到 Firestore,在 ListView 页面上显示。它本身工作正常,但是在我发送它之后,会弹出一个错误,它显示错误是列表视图页面上的时间戳 toDate
活动的顺序是列表视图>发送页面>列表视图。
//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);
}
});
到列表视图页面
//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 时,我对这种事情有印象,所以我尝试首先启动发送活动而不是视图,它成功了,但只是一次,第二次它显示相同的错误,我试图完成onclick to sendpage时整个活动列表视图,仍然不起作用,
Firestore 正在完美地获取数据,并且在重新启动应用程序后,listview 会显示数据,因此该功能正在运行。 建议字段
解决方案
由于以下代码行,您将收到 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)
需要索引。要添加这样的索引,请查看我在以下帖子中的回答:
推荐阅读
- asp.net - 将相关数据添加到身份
- swift - 在 Swift 4 中使用 reduce 将数组与条件连接起来
- express - 使用 `prpl-server` 作为 express 框架时实现`--https-redirect`
- android - 错误:项目正在使用不受支持的 Gradle 版本
- python - KeyError:使用来自 Tensorflow DNNClassifier.predict 的预测方法时出现“预测”
- mapbox - 在 Mapbox 中,使用 setStyle 时如何保留图层?
- dynamics-crm - 使用 Simple.odata.client 库检索 CRM OptionSet 字段
- c# - 如何对存储过程的结果进行排序并返回js?
- python - 使用 Anaconda 编译器在 Anaconda 中从源代码构建 Scipy
- javascript - 在 JS 函数中使用递归的奇怪循环