如何测试firestore中是否存在文档?
我想测试firestore中是否存在文档,我尝试了以下操作:
mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Settings activity = activityReference.get();
if (documentSnapshot.exists()) {
usable = false;
Log.d("checkIfUsable", String.valueOf(usable));
} else {
usable = true;
Log.d("checkIfUsable", String.valueOf(usable));
}
}
});
我可以在日志中看到消息,但变量
可用的
未及时更新。之后的代码应该在完成文档存在性测试后执行。
我认为使用AsyncTask可能会起作用,但事实并非如此。以下是我所做的:
private static class checkIfUsable extends AsyncTask<String, Void, Void> {
private WeakReference<Settings> activityReference;
// only retain a weak reference to the activity
checkIfUsable(Settings context) {
activityReference = new WeakReference<>(context);
}
private WeakReference<Application> appReference;
checkIfUsable(Application context) {
appReference = new WeakReference<>(context);
}
@Override
protected Void doInBackground(String... strings) {
DocumentReference mDocRef = FirebaseFirestore.getInstance().document("savedSampleData/" + Arrays.toString(strings));
mDocRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Settings activity = activityReference.get();
if (documentSnapshot.exists()) {
activity.usable = false;
Log.d("checkIfUsable", String.valueOf(activity.usable));
} else {
activity.usable = true;
Log.d("checkIfUsable", String.valueOf(activity.usable));
}
}
});
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Settings activity = activityReference.get();
if (activity.usable) {
final SharedPreferences sharedPreferences = activity.getSharedPreferences(SETTINGS_SHARED_PREF_FILE_KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PERSONAL_SAMPLE_CODE_KEY, String.valueOf(activity.text));
editor.apply();
activity.update();
} else {
Toast.makeText(appReference.get(), R.string.something_went_wrong_check_internet_or_use_other_code, Toast.LENGTH_LONG).show();
}
}
}
我在构造器上发现了这个错误
new checkIfUsable().execute();
无法解析构造函数
是否有其他方法检查文档是否存在?
我是否将AsyncTask编码错误?
谢谢你的帮助