RecylerView Adapter in android Firebase is not quite syncing - android

I am creating a program, where user can update post, and other user and same user can react there. For that, I have implemented the love button. So this works this way, I have saved a unique id in the DatabaseReference and other reference for uniquekey for easiness. So, whenever, the user clicks on love button, it must update the total reaction of the node by increasing it to one. The problem I am getting is, whenever I press the love button key, it doesn't call the uniqueID I need. The uniqueId I am getting from model class from viewholder is not the post I have reacted to.
public class LatestFragment extends Fragment {
private RecyclerView latestFragmentRecyclerView;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mAuth;
private static Context context;
private static boolean firstTime;
private static String totalVotes;
private static String uniqueKey;
private static DatabaseReference reactionDatabaseReference;
private static DatabaseReference uniqueKeysReferences;
private static Boolean userReactState;
private static List<String> allUniqueKeys;
public LatestFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_latest,container,false);
latestFragmentRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerViewForLatestFragment);
latestFragmentRecyclerView.setHasFixedSize(true);
userReactState = false;
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
latestFragmentRecyclerView.setLayoutManager(layoutManager);
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
reactionDatabaseReference=FirebaseDatabase.getInstance().getReference().child("PostReactions");
uniqueKeysReferences = FirebaseDatabase.getInstance().getReference().child("UniqueKeys");
mDatabaseReference.keepSynced(true);
firstTime = true;
return v;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<Posts, PostViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Posts, PostViewHolder>(
Posts.class, R.layout.each_post_layout, PostViewHolder.class, mDatabaseReference
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder,final Posts model, int position) {
Context c = getActivity();
context = c;
uniqueKey = model.getUnique();
viewHolder.setUsername(model.getUsername());
viewHolder.setCaption(model.getCaption());
viewHolder.setTime(model.getTime());
viewHolder.setImage(model.getImage(),c);
viewHolder.setCurrentUserImage(model.getUserPhoto(),c);
viewHolder.imageViewIfUserClicked(model.getCurrentUserReaction(),c);
totalVotes = model.getTotalReactions();
}
};
latestFragmentRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
View theRecyclingView;
private Button loveButton ;
public PostViewHolder(View itemView) {
super(itemView);
theRecyclingView = itemView;
loveButton = (Button) theRecyclingView.findViewById(R.id.loveButton);
loveButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId()==loveButton.getId())
{
allUniqueKeys = new ArrayList<>();
int position = getAdapterPosition();
Log.e("UniqueKey", String.valueOf(position));
uniqueKeysReferences.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot x : dataSnapshot.getChildren()) {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(firstTime==true)
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
firstTime = false;
int vote= Integer.valueOf(totalVotes);
vote++;
totalVotes = String.valueOf(vote);
reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("true").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
firstTime = true;
int vote= Integer.valueOf(totalVotes);
vote--;
totalVotes = String.valueOf(vote);
reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("false").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
else
{
Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public void setUsername(String username)
{
TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.userWhoPostedUserName);
mUsername.setText(username);
}
public void setCaption(String caption) {
TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.captionForPic);
mUsername.setText(caption);
}
public void setImage(final String image, final Context c) {
final ImageView imageView = (ImageView) theRecyclingView.findViewById(R.id.userUploadedImageView);
Picasso.with(c).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(c).load(image).into(imageView);
}
});
}
public void setTime(String time) {
TextView time_of_posting = (TextView) theRecyclingView.findViewById(R.id.timeOfPosting_each_post_layout);
time_of_posting.setText(time);
}
public void setCurrentUserImage(final String userPhoto, final Context c) {
final CircleImageView imageView = (CircleImageView) theRecyclingView.findViewById(R.id.userWhoPostedCircleImageView);
Picasso.with(c).load(userPhoto).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(c).load(userPhoto).into(imageView);
}
});
}
public void imageViewIfUserClicked(String currentUserReaction, final Context c) {
//reactionDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
// #Override
//public void onDataChange(DataSnapshot dataSnapshot) {
// String CurrentuserReaction = dataSnapshot.child(uniqueKey).child("TotalReactions").child("CurrentUserReaction").getValue().toString();
// userReactState = Boolean.parseBoolean(CurrentuserReaction);
//}
//#Override
//public void onCancelled(DatabaseError databaseError) {
//
// }
// });
if(userReactState==false) {
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
}
else
{
loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
}
}
}
}

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 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

How to search list of data from firestore using searchView

I already retrieve the data from FireStore successfully, and i want to search list of data using SearchView, but it doesnt show anything in recyclerView when i try to search in Searchview.
Here is my code for Main Activity. I retrieve the list of data using query and show in recycler View.
public class MainActivity extends AppCompatActivity {
private final static String TAG = MainActivity.class.getSimpleName();
private RecyclerView recyclerView;
private FirebaseAuth mAuth;
private FirebaseFirestore db;
private FoodAdapter mAdapter;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Force Login
if (mAuth.getCurrentUser() == null || mAuth.getCurrentUser().getEmail().isEmpty()) {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
recyclerView = findViewById(R.id.recycler_home);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = findViewById(R.id.search);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
getSearch(newText);
return false;
}
});
mAdapter = new FoodAdapter(new FoodAdapter.OnFoodClickListener() {
#Override
public void OnClick(FoodModel food) {
Intent intent = new Intent(MainActivity.this, FoodActivity.class);
intent.putExtra("id", food.getId());
startActivity(intent);
}
getFoodData();
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(mAdapter);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
getFoodData();
}
public void getSearch(String s){
mAdapter.clear();
Query que = db.collection("Food");
que.whereEqualTo("title", s);
que
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()) {
for (DocumentSnapshot docSnap : documentSnapshots.getDocuments()) {
FoodModel model = docSnap.toObject(FoodModel.class);
model.setId(docSnap.getId());
loadSticker(model);
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
});
}
public void getFoodData() {
mAdapter.clear();
Query query = db.collection(“Food”);
query
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()) {
for (DocumentSnapshot docSnap : documentSnapshots.getDocuments()) {
FoodModel model = docSnap.toObject(FoodModel.class);
model.setId(docSnap.getId());
loadSticker(model);
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
});
}
public void loadSticker(final FoodModel foodModel) {
db
.collection("beverage")
.whereEqualTo("name", foodModel.getBeverage())
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.getDocuments().get(0).exists()) {
BeverageModel model = documentSnapshots.getDocuments().get(0).toObject(BeverageModel.class);
FoodModel newFoodModel = foodModel;
newFoodModel.setSticker(model.getSticker());
mAdapter.addItem(newFoodModel);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
});
}
}
Here is the adapter code, which i apply filter for searchView. Anybody knows whats the error in my code for adapter.
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private List<FoodModel> foodModels;
private List<FoodModel>foodModelsList;
private OnFoodClickListener listener;
public FoodAdapter(OnFoodClickListener listener) {
foodModels = new ArrayList<>();
this.foodModelsList = foodModels;
this.listener = listener;
}
#Override
public FoodViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_food, parent, false);
return new FoodViewHolder(view);
}
#Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
FooModel model = foodModels.get(position);
holder.title.setText(model.getTitle());
holder.description.setText(model.getDescription());
Picasso.get().load(model.getSticker()).into(holder.sticker);
}
#Override
public int getItemCount() {
return foodModels.size();
}
public void addItem(FoodModel food){
foodModels.add(food);
notifyDataSetChanged();
}
class FoodViewHolder extends RecyclerView.ViewHolder {
private TextView name, description;
private ImageView sticker;
FoodViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title);
sticker = itemView.findViewById(R.id.img_sticker);
description = itemView.findViewById(R.id.tv_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
listener.OnClick(foodModels.get(position));
}
});
}
}
public interface OnFoodClickListener{
void OnClick(FoodModel food);
}
}

How to hide particular item in RecyclerView and deleting its space

I want to hide the current user in RequestsFragment in recyclerview. I tried to setVisibility feature. The current user's informantions are not seen to him. But there is a space still in recyclerview. How can i also delete space between other items. I mean if I have sent a request to other users I dont want to see myself at requests fragment.
public class RequestsFragment extends Fragment {
private RecyclerView recyclerView_friendRequestsList;
private View mainView;
private DatabaseReference friendRequestsDatabaseReference;
private DatabaseReference usersDatabaseReference;
private FirebaseAuth firebaseAuth;
private String current_user_id;
public RequestsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.fragment_requests, container, false);
recyclerView_friendRequestsList = mainView.findViewById(R.id.friendRequests_list);
recyclerView_friendRequestsList.setHasFixedSize(true);
recyclerView_friendRequestsList.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseAuth = FirebaseAuth.getInstance();
current_user_id = firebaseAuth.getCurrentUser().getUid();
friendRequestsDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friend Requests");
friendRequestsDatabaseReference.keepSynced(true);
usersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
usersDatabaseReference.keepSynced(true);
return mainView;
}
#Override
public void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<FriendRequests, RequestsFragment.FriendRequestsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<FriendRequests, FriendRequestsViewHolder>(
FriendRequests.class,
R.layout.users_single_layout,
RequestsFragment.FriendRequestsViewHolder.class,
friendRequestsDatabaseReference
) {
#Override
protected void populateViewHolder(final FriendRequestsViewHolder viewHolder, FriendRequests model, final int position) {
final String user_id = getRef(position).getKey();
friendRequestsDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
usersDatabaseReference.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!user_id.equals(current_user_id)) {
final String user_displayName = dataSnapshot.child("display_name").getValue().toString();
final String user_thumbImage = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
viewHolder.setUserOnline(userOnline);
}
viewHolder.setName(user_displayName);
viewHolder.setImage(user_thumbImage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
});
} else {
viewHolder.mView.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
friendRequestsDatabaseReference.child(current_user_id).child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("request_type")) {
String request_type = dataSnapshot.child("request_type").getValue().toString();
viewHolder.setRequest_type(request_type);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
recyclerView_friendRequestsList.setAdapter(firebaseRecyclerAdapter);
}
public static class FriendRequestsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendRequestsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView userNameView = mView.findViewById(R.id.user_single_displayName);
userNameView.setText(name);
}
public void setRequest_type(String request_type) {
TextView userStatusView = mView.findViewById(R.id.user_single_status);
userStatusView.setText(request_type);
}
public void setImage(final String thumb_image) {
CircleImageView userImageView = mView.findViewById(R.id.user_single_image);
Picasso.get().load(thumb_image).placeholder(R.mipmap.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = mView.findViewById(R.id.user_single_online);
if (online_status.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}

load image and video in recylerview

I have an adapter class where I am able to load all video from Firebase. But the problem is I can't load both, image and video in one RecyclerView
See what I have done:
I am using toro library to auto play video if your wondering and ExoPlayer to play video
This is my adapter class
public class MainFeedAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
private static final String TAG = "MainfeedAdapter";
private List<Photo> moviesList;
private DatabaseReference mReference;
private Context mContext;
private String currentUsername = "";
private int mLayoutResource;
private LayoutInflater mInflater;
private Photo photo;
private MyViewHolder mHolder;
public class MyViewHolder extends RecyclerView.ViewHolder implements ToroPlayer{
static final int LAYOUT_RES = R.layout.main_list;
private ExoPlayerViewHelper helper;
private CircleImageView profile_image;
//private String likeString;
private TextView username,time,caption,likes,comment,stars;
private SquareImageView image;
private LikeButton mHeart,Star;
private UserAccountSettings userAccountSettings = new UserAccountSettings();
private User user = new User();
private StringBuilder users;
private String mLIkeString;
private String mStarString;
private boolean likeByCurrentUSer;
private boolean starbycurrentuser;
private DatabaseReference mNotification;
private ImageView commentBubble;
private Uri mediaUri;
#BindView(R.id.main_post_image2)
PlayerView playerView;
private CardView video;
public MyViewHolder(View view) {
super(view);
profile_image = (CircleImageView)view.findViewById(R.id.post_profile_photo);
username = (TextView) view.findViewById(R.id.main_username);
time = (TextView) view.findViewById(R.id.main_image_time_posted);
caption = (TextView) view.findViewById(R.id.main_image_caption);
likes = (TextView) view.findViewById(R.id.main_likes);
comment = (TextView) view.findViewById(R.id.main_showcomments);
image = (SquareImageView) view.findViewById(R.id.main_post_image);
mHeart = (LikeButton) view.findViewById(R.id.main_heart);
Star = (LikeButton) view.findViewById(R.id.main_star);
stars= (TextView)view.findViewById(R.id.stars);
commentBubble = (ImageView)view.findViewById(R.id.main_comments) ;
mNotification = FirebaseDatabase.getInstance().getReference().child("notification");
mReference = FirebaseDatabase.getInstance().getReference();
ButterKnife.bind(this, itemView);
video = (CardView)view.findViewById(R.id.video_posts);
}
#NonNull
#Override
public View getPlayerView() {
return playerView;
}
#NonNull
#Override
public PlaybackInfo getCurrentPlaybackInfo() {
return helper != null ? helper.getLatestPlaybackInfo() : new PlaybackInfo();
}
#Override
public void initialize(#NonNull Container container, #Nullable PlaybackInfo playbackInfo) {
if (helper == null) {
helper = new SimpleExoPlayerViewHelper(container, this, mediaUri);
}
helper.initialize(playbackInfo);
}
// called from Adapter to setup the media
void bind( Uri item, List<Photo> payloads) {
if (item != null) {
mediaUri = item;
}else {
video.setVisibility(View.GONE);
}
}
#Override
public void play() {
if (helper != null) helper.play();
}
#Override
public void pause() {
if (helper != null) helper.pause();
}
#Override
public boolean isPlaying() {
return helper != null && helper.isPlaying();
}
#Override
public void release() {
if (helper != null) {
helper.release();
helper = null;
}
}
#Override
public boolean wantsToPlay() {
return ToroUtil.visibleAreaOffset(this, itemView.getParent()) >= 0.85;
}
#Override
public int getPlayerOrder() {
return getAdapterPosition();
}
#Override
public void onSettled(Container container) {
}
}
public TestAdapter(List<Photo> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_list, parent, false);
mContext = parent.getContext();
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
photo = moviesList.get(position);
mHolder = holder;
holder.users = new StringBuilder();
getCurrentUsername();
getLikesString(mHolder);
getStarString(mHolder);
holder.bind(Uri.parse(photo.getVideo_path()),moviesList);
//get the profile image and username
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
// currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
Log.d(TAG, "onDataChange: found user: "
+ singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profile_image);
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
holder.userAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
holder.commentBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query userQuery = mReference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
holder.user = singleSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private boolean rechedendoflist(int position){
return position == getItemCount() -1;\
}
#Override
public int getItemCount() {
return moviesList.size();
}
public Photo getItem(int position) {
return moviesList.get(position);
}
private void getCurrentUsername(){
Log.d(TAG, "getCurrentUser: ");
Log.d(TAG, "getCurrentUsername: retrieving user account settings");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please help me guys!. Thanks in Advance!.
TheRecyclerView has ability to show items in multiple types.
In your case you can define two ViewType. one for Images and another for Videos.
Search about RecyclerView with multiple view types.
Take a look at here and this.
Also here is a question and answers about it.

Categories

Resources