Reputation: 133
I have the codes below to load and filter the data from Firebase Firestore to a recycle view that Loads all the Filtered data, everything is working fine , but , when I go delete the selected item from the searched list, it does delete from the Firestore data on the web but still loaded by the Search recycle view after been deleted , looks like the Adatper still have the Data and didn't remove it after been deleted , please take a look to the codes Below in both deletenote() and getnotes() methods :-
package com.example.boc.main;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.example.boc.PhoneNumbers.NoteRecyclerViewAdapter;
import com.example.boc.PhoneNumbers.ViewNoteDialog;
import com.example.boc.models.Search;
import com.example.boc.search.SearchRecyclerViewAdapter;
import com.example.boc.R;
import com.example.boc.Interface.IMainActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import com.example.boc.models.Note;
/**
* Created by User on 5/14/2018.
*/
public class Search_test extends AppCompatActivity implements
View.OnClickListener,
IMainActivity,
SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "MainActivity";
//Firebase
private FirebaseAuth.AuthStateListener mAuthListener;
//widgets
private FloatingActionButton mFab, mFab2;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
public FirebaseFirestore db = FirebaseFirestore.getInstance();
//vars
private View mParentLayout;
private ArrayList<Search> mSearch = new ArrayList<>();
private ArrayList<Note> mNotes = new ArrayList<>();
private DocumentReference noteRef = db.collection("notes").document();
private CollectionReference notesCollectionRef = db.collection("notes");
private NoteRecyclerViewAdapter mNoteRecyclerViewAdapter;
private SearchRecyclerViewAdapter mSearchRecyclerViewAdapter;
private DocumentSnapshot mLastQueriedDocument;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.search_recycler);
mParentLayout = findViewById(android.R.id.content);
mRecyclerView = findViewById(R.id.recycler_view_search);
EditText userinput = findViewById(R.id.userInputtxt);
initRecyclerView();
getNotes();
}
@Override
public void onBackPressed() {
super.onBackPressed();
Animatoo.animateFade(Search_test.this); //fire the slide left animation
}
@Override
public boolean onCreatOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar, menu);
return true;
}
@Override
public void deleteNote(final Note note) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference noteRef = db
.collection("notes").document(note.getNote_id());
noteRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
makeSnackBarMessage("Deleted note");
mRecyclerView.setAdapter(null);// trying to make the recycle view remove the adapter but still loading the old list //
} else {
makeSnackBarMessage("Failed. Check log.");
}
}
});
}
@Override
public void onRefresh() {
}
private void getNotes() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
final EditText userinput = findViewById(R.id.userInputtxt);
CollectionReference notesCollectionRef = db
.collection("notes");
Query notesQuery = null;
if (mLastQueriedDocument != null) {
notesQuery = notesCollectionRef
.orderBy("timestamp", Query.Direction.ASCENDING);
} else {
notesQuery = notesCollectionRef
.orderBy("timestamp", Query.Direction.ASCENDING);
}
notesQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
String data = "";
for (final QueryDocumentSnapshot document : task.getResult()) {
Note note = document.toObject(Note.class);
mNotes.add(note);
if (userinput == null) {
mRecyclerView.setAdapter(null);
}
if (userinput != null) {
userinput.addTextChangedListener(
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
final String userinputString = userinput.getText().toString();
mSearch.clear();
for (Note note : mNotes) {
if (note.getTitle().contains(userinputString)) {
if (note != null) {
mSearch.add(note);
mSearchRecyclerViewAdapter = new SearchRecyclerViewAdapter(Search_test.this, mSearch);
mRecyclerView.setLayoutManager(new LinearLayoutManager(Search_test.this));
mRecyclerView.setAdapter(mSearchRecyclerViewAdapter);
mSearchRecyclerViewAdapter.notifyDataSetChanged();
}
}
}
}
}
);
}
}
if (task.getResult().size() != 0) {
mLastQueriedDocument = task.getResult().getDocuments()
.get(task.getResult().size() - 1);
}
mSearchRecyclerViewAdapter.notifyDataSetChanged();
} else {
makeSnackBarMessage("Query Failed. Check Logs.");
}
}
});
}
private void initRecyclerView() {
if (mNoteRecyclerViewAdapter == null) {
mSearchRecyclerViewAdapter = new SearchRecyclerViewAdapter(this, mSearch);
}
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mSearchRecyclerViewAdapter);
}
@Override
public void updateNote(final Note note) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference noteRef = db
.collection("notes")
.document(note.getNote_id());
noteRef.update(
"title", note.getTitle(),
"content", note.getContent(), "pos", note.getpos()
).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
makeSnackBarMessage(" تم تحديث المعلومات");
} else {
makeSnackBarMessage("حدث خطأ , يرجى اعادة المحاولة");
}
}
});
}
@Override
public void onNoteSelected(Note note) {
ViewNoteDialog dialog = ViewNoteDialog.newInstance(note);
dialog.show(getSupportFragmentManager(), getString(R.string.dialog_view_note));
}
@Override
public void createNewNote(String title, String content, String pos) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DocumentReference newNoteRef = db
.collection("notes")
.document();
Note note = new Note();
note.setTitle(title);
note.setContent(content);
note.setPos(pos);
note.setNote_id(newNoteRef.getId());
note.setUser_id(userId);
newNoteRef.set(note).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
makeSnackBarMessage("تمت اضافة رقم الهاتف للسجل");
getNotes();
} else {
makeSnackBarMessage(" يوجد خطأ , يرجى اعادة المحاولة");
}
}
});
}
private void makeSnackBarMessage(String message) {
Snackbar.make(mParentLayout, message, Snackbar.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
{
}
}
}
Upvotes: 1
Views: 312
Reputation: 133
ANSWER 1
I got it, thanks for you all for your time, the solution was by clearing both array lists that is loaded with old data and filtered data, then notify the adapter, after that recall the get notes() method to reload the new data from the firebase firestore which does not contain the deleted ones anymore :-
@Override
public void deleteNote(final Note note){
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference noteRef = db
.collection("notes").document(note.getNote_id());
noteRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
makeSnackBarMessage("Deleted fgfff");
mNotes.clear();
mSearch.clear();
mSearchRecyclerViewAdapter.notifyDataSetChanged();
getNotes();
}
else{
makeSnackBarMessage("Failed. Check log.");
}
}
});
}
Upvotes: 0
Reputation: 133
ANSWER 2
Iliked this one more as long as it doesnot load the data again , as getnotes() will add the data back every time the user input a char.
noteRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
makeSnackBarMessage("Deleted fgfff");
mNotes.remove(note);
mSearch.remove(note);
mSearchRecyclerViewAdapter.notifyDataSetChanged();
}
else{
makeSnackBarMessage("Failed. Check log.");
}
}
});
}
Upvotes: 0
Reputation: 236
To update the list either you have to delete the note from mNotes with the position of the note selected followed by calling adapter notifyDatasetChanged(). Or you have to load the list again from DB calling getNotes().
Upvotes: 1
Reputation: 657
From what i can tell you never removed the element from the list(mNotes or mSearch i think) that the adapter uses it as data source. So even if it's deleted from Firebase it's still in your list.
Upvotes: 1