Removing all items from recyclerview at ONCE on firebase ui - android

I can delete one at a time in the recyclerview but trying to figure out how to delete the entire element at ONCE in the recyclerview when the finished button is clicked. this is my first time making use of this platform to ask question. Please can someone assist me on this code, i try so many times to remove all items at ONCE from the recyclerview in firebase UI and get error or no results at all. please how to fix this kind of issue and here is my code below. enter image description here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mCartTotal = findViewById(R.id.TV_ShoppingCart_Total);
mBtnFinish = findViewById(R.id.LinearLayout_Cart_Next_Address);
mShopping_RecyclerView = findViewById(R.id.recycler_view_shopping_cart);
mShopping_RecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mShopping_RecyclerView.setHasFixedSize(false);
mBtnFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Please what should i put in here
Intent navigateShippingScreen = new Intent(CartActivity.this, ShippingAddressActivity.class);
navigateShippingScreen.putExtra("Total Price", String.valueOf(overAllTotalPrice));
startActivity(navigateShippingScreen);
finish();
}
});
readDataCart();
}
private void readDataCart() {
FirebaseUser AppUser = FirebaseAuth.getInstance().getCurrentUser();
if (AppUser != null) {
USER_ID = FirebaseAuth.getInstance().getCurrentUser().getUid();
CART_PRODUCT = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query = FirebaseFirestore.getInstance()
.collection("REGISTERED USERS").document(USER_ID)
.collection("CART PRODUCT").orderBy("productTime", Query.Direction.ASCENDING);
options = new FirestoreRecyclerOptions.Builder<PharmacyCart_DataModel>()
.setQuery(query, PharmacyCart_DataModel.class)
.build();
myAdapter = new FirestoreRecyclerAdapter<PharmacyCart_DataModel, myViewHolderCart>(options) {
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull myViewHolderCart holder, int position, #NonNull PharmacyCart_DataModel model) {
holder.mCartTitle.setText(model.getProductCartName());
holder.mCartPrice.setText("RM" + model.getProductCartPrice());
holder.mCartQuantity.setText(model.getProductCartQuantity());
int oneTypeProductPrice = Integer.valueOf(model.getProductCartPrice()) * Integer.valueOf(model.getProductCartQuantity());
overAllTotalPrice = overAllTotalPrice + oneTypeProductPrice;
mCartTotal.setText("RM " + String.valueOf(overAllTotalPrice));
holder.mDeleteProductCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
_deleteCartItemNow(holder);
int oneTypeProductPrice = Integer.valueOf(model.getProductCartPrice()) * Integer.valueOf(model.getProductCartQuantity());
overAllTotalPrice = overAllTotalPrice - oneTypeProductPrice;
mCartTotal.setText("RM " + String.valueOf(overAllTotalPrice));
}
});
}
#NonNull
#Override
public myViewHolderCart onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart_product, parent, false);
return new myViewHolderCart(v);
}
};
mShopping_RecyclerView.setAdapter(myAdapter);
}
}
private void _deleteCartItemNow(myViewHolderCart holder) {
_deleteCartItem(holder.getAdapterPosition());
}
private void _deleteCartItem(int position) {
myAdapter.getSnapshots().getSnapshot(position).getReference().delete();
}
#Override
protected void onStart() {
super.onStart();
myAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
myAdapter.stopListening();
}

Related

onBindViewHolder inside FirestoreRecyclerAdapter only works in Debug mode

I have a list of students shown on a RecyclerView and retrieving data from Firebase I want to check a checkbox if they are inside a group. It apparently works, but only in Debug mode.
Whenever I try to do a normal run it does nothing (only shows the list, but none of the checkboxes are checked).
#Override
protected void onBindViewHolder(#NonNull ListViewAdapter.ViewHolder holder, int position, #NonNull Estudiante estudiante) {
DocumentSnapshot documentSnapshot = getSnapshots().getSnapshot(holder.getAbsoluteAdapterPosition());
String id = documentSnapshot.getId();
holder.nombre.setText(estudiante.getNombre());
estudiantesFirebase = editGrupoFragment.getEstudiantesFirebase();
Log.d("estList","Estudiantes Fireb: "+ estudiantesFirebase.toString());
firestore.collection("Estudiantes")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
ArrayList<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.get("nombre").toString());
}
for (int i = 0; i < estudiantesFirebase.size(); i++){
if(estudiantesFirebase.get(i).equals(holder.nombre.getText().toString())){
Log.d("estList", estudiantesFirebase.get(i) + " => " + holder.nombre.getText().toString());
//TODO: quemar algo
holder.checkBox.setChecked(true);
}
}
} else {
Log.d("estList", "Error getting documents: ", task.getException());
}
}
});
}
Apparently, the ArrayList estudiantesFirebase has no values inside. The other class I am using (to get that array) is the following:
public class EditGrupoFragment extends DialogFragment{
private FragmentEditGrupoBinding binding;
private ListviewItemBinding bindingLV;
TextView txtNombreGrupo, txtNDificultadGrupo;
Spinner spinnerDificultadEditar;
Button btnGuardarCambios;
ListViewAdapter eAdapter;
RecyclerView recyclerView;
FirebaseFirestore firestore;
SearchView searchBar;
Query query;
ArrayList<String> estudiantesFirebase = new ArrayList<>();
String NGRUPO;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments()!=null){
NGRUPO = getArguments().getString("nombre");
}
}
#SuppressLint("NotifyDataSetChanged")
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentEditGrupoBinding.inflate(inflater, container, false);
View root = binding.getRoot();
firestore = FirebaseFirestore.getInstance();
searchBar = root.findViewById(R.id.searchBar);
btnGuardarCambios = root.findViewById(R.id.btnGuardarEditGrupo);
txtNombreGrupo = root.findViewById(R.id.etEditNombreGrupo);
txtNDificultadGrupo = root.findViewById(R.id.txtNDificultadGrupo);
spinnerDificultadEditar= root.findViewById(R.id.spinnerDificultadEditar);
getGrupo();
setUpRecyclerView(root);
search_view();
return root;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnGuardarCambios.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nombre = txtNombreGrupo.getText().toString();
String dificultad = spinnerDificultadEditar.getSelectedItem().toString();
//String description = txtDescriptionGrupo.getText().toString();
updateGrupo(nombre, dificultad);
}
});
}
private void getGrupo(){
firestore.collection("Temas").document(NGRUPO).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String nombre = documentSnapshot.getString("nombre");
String dificultad = documentSnapshot.getString("dificultad");
estudiantesFirebase = (ArrayList<String>) documentSnapshot.get("estudiantes");
txtNombreGrupo.setText(nombre);
spinnerDificultadEditar.setPrompt("Actual: "+dificultad);
//txtDescriptionGrupo.setText(grupo);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Error al obtener los datos", Toast.LENGTH_SHORT).show();
}
});
}
public ArrayList<String> getEstudiantesFirebase(){
return estudiantesFirebase;
}
private void updateGrupo(String nombre, String dificultad) {
Map<String, Object> map = new HashMap<>();
map.put("nombre", nombre);
map.put("dificultad", dificultad);
firestore.collection("Temas").document(NGRUPO).update(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Tema editado", Toast.LENGTH_SHORT).show();
getDialog().dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Error al editar tema", Toast.LENGTH_SHORT).show();
}
});
}
#SuppressLint("NotifyDataSetChanged")
private void setUpRecyclerView(View view) {
recyclerView = view.findViewById(R.id.searchRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
query = firestore.collection("Estudiantes");
FirestoreRecyclerOptions<Estudiante> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<Estudiante>().setQuery(query, Estudiante.class).build();
eAdapter = new ListViewAdapter(firestoreRecyclerOptions, getActivity(), getActivity().getSupportFragmentManager(),this);
eAdapter.notifyDataSetChanged();
recyclerView.setAdapter(eAdapter);
}
private void search_view() {
searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
textSearch(s);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
textSearch(s);
return false;
}
});
}
private void textSearch(String s) {
FirestoreRecyclerOptions<Estudiante> firestoreRecyclerOptions =
new FirestoreRecyclerOptions.Builder<Estudiante>().setQuery(query.orderBy("nombre")
.startAt(s).endAt(s+"~"), Estudiante.class).build();
eAdapter = new ListViewAdapter(firestoreRecyclerOptions, getActivity(), getActivity().getSupportFragmentManager(),this);
eAdapter.startListening();
recyclerView.setAdapter(eAdapter);
}
#Override
public void onStart() {
super.onStart();
eAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
eAdapter.stopListening();
}
#Override
public void onResume() {
super.onResume();
int width = getResources().getDisplayMetrics().widthPixels;
int height = (getResources().getDisplayMetrics().heightPixels)/2;
getDialog().getWindow().setLayout(width, height);
}
}

Recyclerview won't show items, Firebase Admin SDK, Realtime Database

I'm trying to retrieve some simple data from my database as an Admin, the data has been retrieved, but nothing is shown on the recyclerview.
In the other hand, i was trying to assign a value (String) from the database to a TextView, i was recieving the value, but the TextView was empty, i went to the .xml file and changed the layout_width from android:layout_width="wrap_content" to android:layout_width="match_parent" and it worked! Before that with the simple Firebase Client SDK it was showing the texte even with android:layout_width="wrap_content"
PS: Since i started using the Firebase Admin SDK, I didn't had any issues with writing data to the Realtime database, Or with creating Users. I tried both of them and they works fine.
Here's the retrieving function :
private void RetriveClasses() {
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Classrooms");
mclassrooms.clear();
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Classroom post = snapshot.getValue(Classroom.class);
if (!post.getDeleted().equals("true"))
{
mclassrooms.add(post);
}
mAdapter.notifyDataSetChanged();
System.out.println(post.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
The System.out.println(post.getClassName()); Shows :
I/System.out: L1 ST 2022-2023
L1 ST 2021-2022
L1 ST 2015-2016
These are the class names i'm looking for, which means the reading is succeed, but the recyclerview still won't show any items.
here's my Adapter:
public class ClassroomsAdapter extends RecyclerView.Adapter<ClassroomsAdapter.ViewHolder> {
private Context c;
public List<Classroom> mclassrooms;
public ClassroomsAdapter(List<Classroom> mclassrooms) {
this.mclassrooms = mclassrooms;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
this.c = parent.getContext();
View view = LayoutInflater.from(c).inflate(R.layout.classroom_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Classroom classroom = mclassrooms.get(position);
if (classroom.getClassName().length() >= 20)
{
String className = classroom.getClassName();
holder.classroom_name.setText(className.substring(0,19) + "...");
}
else
{
holder.classroom_name.setText(classroom.getClassName());
}
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(c, R.style.BottomSheetDialogTheme);
View eview = LayoutInflater.from(c).inflate(R.layout.bottom_menu_classroom, null);
eview.findViewById(R.id.Delete_Comment_Btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog progressDialog = new ProgressDialog(c, R.style.MyAlertDialogStyle);
progressDialog.setTitle("Suppression");
progressDialog.setMessage("Traitement...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
DatabaseReference mRoot = FirebaseDatabase.getInstance().getReference("Classrooms");
mRoot.child(classroom.getClassId()).child("deleted").setValue("true", new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
progressDialog.dismiss();
Toast.makeText(c, "Suppression avec succès!", Toast.LENGTH_SHORT).show();
bottomSheetDialog.dismiss();
}
});
}
});
eview.findViewById(R.id.copy_comment_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final BottomSheetDialog bs = new BottomSheetDialog(c, R.style.BottomSheetDialogTheme);
View aview = LayoutInflater.from(c).inflate(R.layout.edit_class_name, null);
EditText name_et = aview.findViewById(R.id.Edition_Comment_Input_Field);
name_et.setText(classroom.getClassName());
aview.findViewById(R.id.update_comment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (name_et.getText().toString().isEmpty()) {
Toast.makeText(c, "Ce champ est requis*", Toast.LENGTH_SHORT).show();
} else {
final ProgressDialog progressDialog = new ProgressDialog(c, R.style.MyAlertDialogStyle);
progressDialog.setTitle("Mise à jour");
progressDialog.setMessage("Traitement...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
DatabaseReference mRoot = FirebaseDatabase.getInstance().getReference("Classrooms");
mRoot.child(classroom.getClassId()).child("className").setValue(name_et.getText().toString(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError error, DatabaseReference ref) {
progressDialog.dismiss();
Toast.makeText(c, "Mise à jour avec succès!", Toast.LENGTH_SHORT).show();
bs.dismiss();
bottomSheetDialog.dismiss();
}
});
}
}
});
aview.findViewById(R.id.close_edit_comment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bs.dismiss();
}
});
bs.setContentView(aview);
bs.show();
}
});
bottomSheetDialog.setContentView(eview);
bottomSheetDialog.show();
return false;
}
});
}
#Override
public int getItemCount() {
return mclassrooms.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView classroom_name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
classroom_name = itemView.findViewById(R.id.class_name);
}
}
}
Thanks for your time.

RecyclerView won't update after deleting file

I have CardViews in RecyclerView and each one has a delete button, when clicked it deletes data from database, remove item from ArrayList on that position and runs the animation.
When deleted it dissapears and creates a copy of it self ,Toast shows that ArrayList is empty/ without that item, but its still there I can click on it and everything, only after refreshing fragment(Changing to another fragment in bottom navigation tab or clicking on the same one) it dissapears.
This is my Adapter:
public class KitAdapter extends RecyclerView.Adapter<KitAdapter.MyViewHolder> {
Context context;
ArrayList<Kit> kitList;
OnKitClickListener clickListener;
FirebaseFirestore db;
FirebaseAuth mAuth;
FirebaseStorage FS;
String userID, saveShare;
ArrayList<String> DRList;
public KitAdapter(Context context, ArrayList<Kit> kitList, OnKitClickListener clickListener, String saveShare, ArrayList<String> DRList) {
this.context = context;
this.kitList = kitList;
this.clickListener = clickListener;
this.saveShare = saveShare;
this.DRList = DRList;
}
public ArrayList<Kit> getKitList() {
return kitList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.kitview, parent, false);
return new MyViewHolder(v, clickListener);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Kit kit = kitList.get(position);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
FS = FirebaseStorage.getInstance();
this.userID = kit.getUserID();
holder.Name.setText(kit.getName());
holder.kcal.setText(kit.getKcalM() / kit.getSavedDays() + "kcal");
holder.prot.setText(kit.getProtM() / kit.getSavedDays() + "g");
holder.uh.setText(kit.getUhM() / kit.getSavedDays() + "g");
holder.mast.setText(kit.getMastM() / kit.getSavedDays() + "g");
holder.numOfDays.setText("Broj dana " + kit.getSavedDays() + "");
holder.NameS = kit.getName();
holder.kcalS = String.valueOf(kit.getKcalM());
holder.protS = String.valueOf(kit.getProtM());
holder.uhS = String.valueOf(kit.getUhM());
holder.mastS = String.valueOf(kit.getMastM());
holder.dayNums = kit.getSavedDays();
holder.DRlist = this.DRList;
holder.userID = this.userID;
if(saveShare.equals("Saved")){
if(kit.getShared().equals("No")) {
holder.saveShare.setImageResource(R.drawable.ic_upload_black_24dp);
holder.saveShare.setTag(R.drawable.ic_upload_black_24dp);
}else{
holder.saveShare.setImageResource(R.drawable.ic_file_download_done_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_done_black_24dp);
}
if(!userID.equals(mAuth.getCurrentUser().getUid())){
holder.saveShare.setVisibility(View.GONE);
}
}else if(saveShare.equals("Search")){
holder.saveShare.setImageResource(R.drawable.ic_file_download_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_black_24dp);
holder.delete.setVisibility(View.GONE);
if(DRList.contains(holder.NameS)){
holder.saveShare.setImageResource(R.drawable.ic_file_download_done_black_24dp);
holder.saveShare.setTag(R.drawable.ic_file_download_done_black_24dp);
}
}
db.collection("Users Data")
.document(this.userID)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
User user = task.getResult().toObject(User.class);
String userName = user.getUsername();
holder.userName.setText(userName);
}
});
FS.getReference().child(this.userID + ".jpg")
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
Picasso.get().load(uri).into(holder.pfp);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
holder.pfp.setImageResource(R.drawable.ic_person_black_24dp);
}
});
}
#Override
public int getItemCount() {
return kitList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView Name, numOfDays, kcal, prot, uh, mast, userName;
ImageView saveShare, delete;
String NameS, kcalS, protS, uhS, mastS, userID;
int dayNums;
OnKitClickListener onKitListener;
CircleImageView pfp;
ArrayList<String> DRlist;
public MyViewHolder(#NonNull View itemView, OnKitClickListener onKitListener) {
super(itemView);
Name = itemView.findViewById(R.id.kitName);
numOfDays = itemView.findViewById(R.id.dayNum);
kcal = itemView.findViewById(R.id.kcal);
prot = itemView.findViewById(R.id.prot);
uh = itemView.findViewById(R.id.uh);
mast = itemView.findViewById(R.id.mast);
userName = itemView.findViewById(R.id.userName);
pfp = itemView.findViewById(R.id.pfp);
saveShare = itemView.findViewById(R.id.saveShare);
delete = itemView.findViewById(R.id.delete);
this.onKitListener = onKitListener;
itemView.setOnClickListener(this);
saveShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKitListener.onKitAdd(getAdapterPosition(), saveShare, Name.getText().toString());
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKitListener.onKitDelete(getAdapterPosition(), (CardView) itemView, userID);
}
});
}
#Override
public void onClick(View v) {
onKitListener.onKitClick(getAdapterPosition(), NameS, kcalS, protS, uhS, mastS, dayNums);
}
}
public interface OnKitClickListener{
void onKitClick(int position, String NameS, String kcalS, String protS, String uhS, String mastS, int dayNums);
void onKitAdd(int position, ImageView addShare, String NameS);
void onKitDelete(int position, CardView card, String userID);
}
}
This is part of code in fragment that deletes item:
#Override
public void onKitDelete(int position, CardView card, String userID) {
Handler handler = new Handler();
if(userID.equals(mAuth.getCurrentUser().getUid())) {
db.collection("Users Data")
.document(userID)
.collection("Kits")
.whereEqualTo("name", kitlist.get(position).getName())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (!task.isSuccessful()) {
return;
}
task.getResult().getDocuments().get(0).getReference()
.delete();
}
});
}else{
db.collection("Users Data")
.document(mAuth.getCurrentUser().getUid())
.collection("Saved Kits")
.document(kitlist.get(position).getName())
.delete();
}
Toast.makeText(getContext(), kitlist.toString(), Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Animation anim = AnimationUtils.loadAnimation(getContext(), R.anim.zoomout);
card.startAnimation(anim);
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(kitlist.isEmpty()){
emptTxt.setVisibility(View.VISIBLE);
kitlist.remove(position);
rec.removeViewAt(position);
adapter.notifyItemRemoved(position);
}
}
},300);
}
}, 150);
}
I tried these combinations:
kitlist.remove(position);
rec.removeViewAt(position);
adapter.notifyItemRemoved(position);
//This one you can see in code above
kitlist.remove(position);
adapter.notifyDataSetChange(position)
And tried making onKitDelete default and using notfiy()/notifyAll()
public interface OnKitClickListener{
void onKitClick(int position, String NameS, String kcalS, String protS, String uhS, String mastS, int dayNums);
void onKitAdd(int position, ImageView addShare, String NameS);
default void onKitDelete(int position, CardView card, String userID){
notify();
}
}
I always get same resoult.
that's easy to update your recycler view with
android ViewModel architechtureAndroid ViewModel Docs

Firestore Recycler adapter - images from firestore

I have a recycler view setup for my chat app. I would like to add it so users are able to send pictures in the chat. I added an image view and added the code to upload the image to firestore. Where I am confused is implementing the code to display it in the recycler view.
Model:
package com.example.android.debateapp.Message;
public class Message {
private String ChatMessage;
private String mChatImageURL;
public Message(){
//Empty constructor needed
}
public Message(String ChatMessage, String mChatImageURL ){
this.ChatMessage = ChatMessage;
this.mChatImageURL = mChatImageURL;
}
public String getChatMessage() {
return ChatMessage;
}
public String getmChatImageURL() {
return mChatImageURL;
}
}
MessageRecyclerAdapter:
public class MessageRecyclerAdapter extends FirestoreRecyclerAdapter<Message, MessageRecyclerAdapter.MessageHolder> {
public MessageRecyclerAdapter(#NonNull FirestoreRecyclerOptions<Message> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MessageHolder holder, int position, #NonNull Message model) {
holder.ChatMessage.setText(model.getChatMessage());
}
#NonNull
#Override
public MessageHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_item, viewGroup, false);
return new MessageHolder(v);
}
class MessageHolder extends RecyclerView.ViewHolder{
TextView ChatMessage;
CircleImageView MessageProfilePicture;
ImageView ChatMessageImage;
public MessageHolder(#NonNull View itemView) {
super(itemView);
ChatMessage = itemView.findViewById(R.id.Message_Chat_Content);
MessageProfilePicture = itemView.findViewById(R.id.Chat_Profile_picture);
ChatMessageImage = itemView.findViewById(R.id.chat_Message_image);
}
public void setChatImage(final String downloadUri) {
ChatMessageImage = itemView.findViewById(R.id.chat_Message_image);
Glide.with(itemView.getContext()).load(downloadUri).into(ChatMessageImage);
}
}
}
ChatActivity
public class ChatActivity extends AppCompatActivity {
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
private static final int GALLERY_PICK = 1;
private ListView mMessageListView;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;
private String mUsername;
private ChildEventListener mChildEventListner;
private ValueEventListener mValueEventListner;
private FirebaseUser mCurrentUser;
private StorageReference storageReference;
private StorageReference mChatPhotosStorageReference;
private Context mContext;
private MessageRecyclerAdapter adapter;
private ImageView chatimage;
private String TESTmessagedoc;
private ImageView chatProfile;
//FIRE STORE
private DocumentReference mMessageDoc;
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = (firebaseFirestore).collection("Messages");
private CollectionReference colRef;
private static final String TAG = ChatActivity.class.getName();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity);
storageReference = FirebaseStorage.getInstance().getReference();
chatProfile = findViewById(R.id.Chat_Profile_picture);
//chatimage = findViewById(R.id.photoImageView);
final String messageDoc = getIntent().getStringExtra("Message_ID");
TESTmessagedoc = messageDoc;
mMessageDoc = firebaseFirestore.collection("Messages").document(messageDoc);
colRef = firebaseFirestore.collection("Messages").document(messageDoc).collection("chats");
mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mSendButton = (Button) findViewById(R.id.sendButton);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Image"), GALLERY_PICK);
}
});
setUpRecyclerView();
// Enable Send button when there's text to send
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String MessageText = mMessageEditText.getText().toString();
Map<String, Object> chatMap = new HashMap<>();
chatMap.put("ChatMessage", MessageText);
chatMap.put("User ID", current_uid);
chatMap.put("Timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Messages")
.document(messageDoc).collection("chats")
.add(chatMap)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
// Clear input box
mMessageEditText.setText("");
}
});
}
private void setUpRecyclerView() {
Query query = colRef.orderBy("Timestamp", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Message> options = new FirestoreRecyclerOptions.Builder<Message>()
.setQuery(query, Message.class)
.build();
adapter = new MessageRecyclerAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_message_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
String imageUri = data.getDataString();
CropImage.activity(Uri.parse(imageUri))
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
final String current_user_id = mCurrentUser.getUid();
final String randomName = UUID.randomUUID().toString();
final StorageReference filepath = storageReference.child("chat_photos").child(randomName + ".JPG");
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
Map<String, String> newImageUrl = new HashMap<>();
newImageUrl.put("image", downloadUrl);
firebaseFirestore.collection("Messages").document(TESTmessagedoc).collection("chats")
.add(newImageUrl)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
/*
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//The download url
final String downloadUrl =
uri.toString();
Log.d("tag", downloadUrl);
if (!downloadUrl.equals("default")) {
// I changed this to glide since i thought picasso was the problem.
// Picasso still should work. Glide is recommended by google tho
Glide.with(getApplicationContext()).load(downloadUrl).into(chatProfile);
}
}
});
*/
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "There was some error in saving Changes.", Toast.LENGTH_LONG).show();
}
});
}
});
}
});
}
}
}}
In the model class i have added getmChatImageURL
In the MessageRecyclerAddapter i added setChatImage
where i am stuck (i think) is in my MessageRecyclerAdapter on my onBindViewHolder i need to set it but i am unsure on how to go about it because i dont know how i would load it into the drawable
Update:
In my MessageRecyclerAdapter i added this
#Override
protected void onBindViewHolder(#NonNull MessageHolder holder, int position, #NonNull Message model) {
holder.ChatMessage.setText(model.getChatMessage());
holder.setChatImage(model.getmChatImageURL());
}
the app run but when i go to upload a image to firestore and the app attempts to display it i get this in the log
W/Glide: Load failed for null with size [0x0]
class com.bumptech.glide.load.engine.GlideException: Received null model
the image is being stored in firestore as a url so i believe the error has something to do with the adapter setup not sure though.
Update 2
I think im on the right track
i changed my adapter class
MessageRecyclerAdapter:
public class MessageRecyclerAdapter extends FirestoreRecyclerAdapter<Message, MessageRecyclerAdapter.MessageHolder> {
private Context mcontext;
public MessageRecyclerAdapter(#NonNull FirestoreRecyclerOptions<Message> options ) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MessageHolder holder, int position, #NonNull Message model) {
holder.ChatMessage.setText(model.getChatMessage());
Glide.with(mcontext.getApplicationContext())
.load(model.getmChatImageURL())
.into(holder.ChatMessageImage);
}
#NonNull
#Override
public MessageHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_item, viewGroup, false);
return new MessageHolder(v);
}
class MessageHolder extends RecyclerView.ViewHolder{
TextView ChatMessage;
CircleImageView MessageProfilePicture;
ImageView ChatMessageImage;
public MessageHolder(#NonNull View itemView) {
super(itemView);
ChatMessage = itemView.findViewById(R.id.Message_Chat_Content);
MessageProfilePicture = itemView.findViewById(R.id.Chat_Profile_picture);
ChatMessageImage = itemView.findViewById(R.id.chat_Message_image);
}
}
}
i added the glide set image into the onbind the error i am facing now when running the code is
android.content.Context android.content.Context.getApplicationContext()' on a null object reference
I also tried
Glide.with(holder.ChatMessageImage.getContext())
.load(model.getmChatImageURL())
.into(holder.ChatMessageImage);
the app runs i am able to successfully upload an image to firestore but then glide throws
W/Glide: Load failed for null with size [0x0]
class com.bumptech.glide.load.engine.GlideException: Received null model
im unsure on how to debug this because when i hook the debugger up to the glide code in the onbind it triggers as soon as the activity is launched
If you already know the imageUrl then just pass it in like this
#Override
protected void onBindViewHolder(#NonNull MessageHolder holder, int position, #NonNull Message model) {
holder.ChatMessage.setText(model.getChatMessage());
holder.setChatImage(imageUrl)
}

how to view user posts friends - Firestore

How could I view the posts, only from friends?
in this example I would like to display in RecyclerView only the posts of my friends. In this case the user 15. (certainly is several friends, I put only one to exemplify)
Structure - database:
USERS
-user01 (current user)
-name: John
-age: 20
--friends
----user10
----user15
-POSTS
--idpost_98685754
---user_post: user15
---title_post: Title
---photo: link
-posts
--idpost_41254d4554s1
---user_post: user40
---title_post: Title
---photo: link
-posts
--idpost_121221sss1
---user_post: user15
---title_post: Title 2
---photo: link 2
-posts
--idpost_9865565555
---user_post: user15
---title_post: Title 3
---photo: link 3
I currently use only the simple order and limit functions explained in the documentation. This is the first time I need to do something like that.
EDIT:
CODE - FRAGMENT:
/*Firebase*/
mDb = FirebaseFirestore.getInstance();
mQuery = mDb.collection("Posts");
Query mQueryNew = mQuery.orderBy("timestamp", Query.Direction.DESCENDING);
/* Recycler */
mCardFeedList = (RecyclerView) view.findViewById(id.cardFeedUser_list);
mCardFeedList.setHasFixedSize(true);
mCardFeedList.setItemViewCacheSize(20);
mCardFeedList.setDrawingCacheEnabled(true);
mAdapter = new PostsAdapter(mQueryNew, this){
#Override
protected void onDataChanged() {
if (getItemCount() == 0) {
mCardFeedList.setVisibility(View.GONE);
} else {
mCardFeedList.setVisibility(View.VISIBLE);
}
}
};
llmanager = new LinearLayoutManager(getActivity());
mCardFeedList.setLayoutManager(llmanager);
mCardFeedList.setAdapter(mAdapter);
/*START*/
if (mAdapter != null) {
mAdapter.startListening();
}
ADAPTER:
public class PostsAdapter extends FirestoreAdapter<PostsAdapter.ViewHolder> {
public interface OnPostsListner{
void onPostSelected(DocumentSnapshot post);
void onLikeSelected(DocumentSnapshot like);
void onCurtidasSelected(DocumentSnapshot curtidas);
void onFotoSelected(DocumentSnapshot foto);
void onCommentsSelected(DocumentSnapshot coments);
}
private OnPostsListner mListner;
public PostsAdapter (Query query, OnPostsListner listner){
super(query);
mListner = listner;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.card_feed_user_row, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListner);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private Boolean mIsliked = false;
#BindView(R.id.tvCardFeedUser_nome)
TextView nomeUser;
#BindView(R.id.tvCardFeedUser_horario)
TextView horaFeed;
#BindView(R.id.tvCardFeedUser_desc)
TextView descFeed;
#BindView(R.id.ivCardFeedUser_image)
ImageView imageFeed;
#BindView(R.id.secaoLike)
LinearLayout curtir;
#BindView(R.id.secaoComments)
LinearLayout comentarios;
#BindView(R.id.tv_card_feed_linear_curtidas)
LinearLayout linear_curtidas;
#BindView(R.id.idBtnLike)
TextView btnLike;
#BindView(R.id.tv_card_feed_numero_curtidas)
TextView curtidas;
#BindView(R.id.tv_card_feed_nome_curtida)
TextView nome_curtidas;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnPostsListner listener) {
final Posts ref = snapshot.toObject(Posts.class);
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final FirebaseUser mCurrentUser = mAuth.getCurrentUser();
nomeUser.setText(ref.getNome_user());
descFeed.setText(ref.getDesc());
//Foto
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).networkPolicy(NetworkPolicy.OFFLINE).into(imageFeed, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(itemView.getContext()).load(ref.getImage()).placeholder(R.drawable.bck_padrao).into(imageFeed);
}
});
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yy HH:mm");
String novaData = formatter.format(ref.getTimestamp());
horaFeed.setText(novaData);
/*CLICKS*/
curtir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onLikeSelected(snapshot);
}
}
});
imageFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onFotoSelected(snapshot);
}
}
});
comentarios.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCommentsSelected(snapshot);
}
}
});
linear_curtidas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onCurtidasSelected(snapshot);
}
}
});
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onPostSelected(snapshot);
}
}
});
}
}
}
To achieve this, you need to query your database twice using nested query. First of all you need to query the database to get all the friends id that correspond to a single user and then based on those ids to query the database for the second time to display only the post de correspond to those particular friends.
One thing to note is that this cannot be done in a single query.

Categories

Resources