Я использую FirestoreRecyclerAdapter для приложения для создания заметок, и я обнаружил, что оно не добавляет документы, которые добавляются к запросу при отключении до тех пор, пока устройство не подключится к сети.
Поэтому я пытаюсьОбойти эту проблему, есть ли у кого-нибудь хорошие предложения?
Странная вещь в этом заключается в том, что он на самом деле удаляет документы, которые больше не соответствуют запросу, без необходимости выходить в интернет.
Вотнемного кода, так что вы можете попробовать это сами: вы можете увидеть весь код в моем проекте Github и / или загрузить APK напрямую с здесь
Когда я изменяю логическую переменную trash
объекта (который преобразуется в документы внутри запроса) Note
он исчезает из запроса, когда он больше не является истинным, но когда я возвращаю ему значение true, он больше не появляется. Как только я выхожу в интернет, все работает нормально.
Настройка окна восстановления с запросом и параметрами в моей деятельности:
Query query = db.collection("notes").whereEqualTo("creator", firebaseUser.getUid()).whereEqualTo("trash", true);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new NoteAdapter(options);
recyclerView.setAdapter(adapter);
Адаптер пожарного магазина:
package com.example.firebaseui_firestoreexample.activities.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.firebaseui_firestoreexample.Note;
import com.example.firebaseui_firestoreexample.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import java.util.Objects;
public class NoteAdapter extends FirestoreRecyclerAdapter<Note, NoteAdapter.NoteHolder> {
private OnItemClickListener listener;
public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int i, @NonNull Note model) {
holder.textViewTitle.setText(model.getTitle());
holder.textViewDescription.setText(model.getDescription());
}
@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item, parent, false);
return new NoteHolder(v);
}
public void deleteItem(int position) {
DocumentReference documentReference = getSnapshots().getSnapshot(position).getReference();
documentReference.collection("Reminders").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot :
Objects.requireNonNull(task.getResult()).getDocuments()) {
documentSnapshot.getReference().delete();
}
}
});
documentReference.delete();
}
public void trashItem(int position) {
DocumentReference documentReference = getSnapshots().getSnapshot(position).getReference();
documentReference.collection("Reminders").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot :
Objects.requireNonNull(task.getResult()).getDocuments()) {
documentSnapshot.getReference().update("trash", true);
}
}
});
documentReference.update("trash", true);
}
public void untrashItem(int position) {
DocumentReference documentReference = getSnapshots().getSnapshot(position).getReference();
documentReference.collection("Reminders").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot :
Objects.requireNonNull(task.getResult()).getDocuments()) {
documentSnapshot.getReference().update("trash", false);
}
}
});
documentReference.update("trash", false);
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
NoteHolder(@NonNull View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewDescription = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(view -> {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onItemClick(getSnapshots().getSnapshot(position), position);
}
});
}
}
public interface OnItemClickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
Примечание объект:
package com.example.firebaseui_firestoreexample;
import com.google.firebase.Timestamp;
import java.util.ArrayList;
import java.util.Date;
@SuppressWarnings("WeakerAccess")
public class Note {
private String title;
private String description;
private ArrayList<String> history;
private ArrayList<String> titleHistory;
private ArrayList<String> shared;
private boolean keepOffline;
private boolean loadToCache;
private boolean trash;
private Timestamp created;
private String creator;
@SuppressWarnings("unused")
public Note(){
// empty constructor needed for firebase
}
public Note(String title, String description, Timestamp created, String creator) {
this.title = title;
this.description = description;
this.created = created;
this.creator = creator;
history = new ArrayList<>();
titleHistory = new ArrayList<>();
shared = new ArrayList<>();
keepOffline = false;
loadToCache = false;
trash = false;
}
public Note newNoteVersion(){
return new Note(title,description, new Timestamp(new Date()), creator);
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public ArrayList<String> getHistory() {
return history;
}
public ArrayList<String> getTitleHistory() {
return titleHistory;
}
public Timestamp getCreated() {
return created;
}
public boolean isKeepOffline() {
return keepOffline;
}
public boolean isLoadToCache() {
return loadToCache;
}
public String getCreator() {
return creator;
}
public ArrayList<String> getShared() {
return shared;
}
public boolean isTrash() {
return trash;
}
}