FirebaseRecyclerOptions query for certain array of keys - java

firebase database
I should extract only certain keys from drinkCategories and display them in FirebaseRecyclerOptions. I'm wondering how should I manipulate the query or FirebaseDatabase reference to only look for specific keys.
Edit: below is my code, arrayOfCategories inside equalTo is not real array, just a representation of what I want to acomplish. "equalTo" takes one string but is there another way to query only certain keys, example i want to query only by keys category-id-7 and category-id-9 (these two keys are stored inside arrayOfCategories), ignore all other keys.
categoriesRef = FirebaseDatabase.getInstance().getReference("drinksCategories");
Query query = categoriesRef.orderByKey().equalTo(arrayOfCategories);
FirebaseRecyclerOptions<Category> options = new FirebaseRecyclerOptions.Builder<Category>()
.setQuery(query, Category.class)
.build();
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder holder, int position, #NonNull Category model) {
String categoryId = getRef(position).getKey();
categoriesRef.child(categoryId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.hasChild("image")) {
Toast.makeText(getActivity(), snapshot.getValue(Category.class).getName(), Toast.LENGTH_SHORT).show();
String description = snapshot.child("description").getValue().toString();
String profileImage = snapshot.child("image").getValue().toString();
String name = snapshot.child("name").getValue().toString();
int id = getResources().getIdentifier(profileImage, "drawable", getActivity().getPackageName());
Drawable drawable;
if (id == 0) {
id = getResources().getIdentifier("no_image", "drawable", getActivity().getPackageName());
drawable = getResources().getDrawable(id);
}
else
drawable = getResources().getDrawable(id);
Glide.with(getActivity()).load(drawable).centerCrop().into(holder.imageView);
holder.txtMenuName.setText(name);
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
recyclerMenu.setVisibility(View.GONE);
insertDrinks(name);
recyclerMenuDrinks.setVisibility(view.VISIBLE);
}
});
}
else {
String name = snapshot.child("name").getKey().toString();
String description = snapshot.child("description").getKey().toString();
holder.txtMenuName.setText(name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.menu_item, parent, false);
return new MenuViewHolder(view);
}
};
recyclerMenu.setAdapter(adapter);
adapter.startListening();

Related

I am trying to search using an edit text from firebase realtime database

It is supposed to show the data and filter when I search but it is not showing any data. I thought I wrote some pretty decent code but I can't find my mistake.
I have a model class with jobTitle, company, experience, age, pay, and type.
I have made a separate layout XML file.
Here is the firebase realtime database structure.
here is the model class.
Here is the java code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showjobs);
ref = FirebaseDatabase.getInstance().getReference("jobs");
searchbtn = findViewById(R.id.searchjobbtn);
searchtxt = findViewById(R.id.searchjobtxt);
result = (RecyclerView) findViewById(R.id.results);
result.setHasFixedSize(true);
result.setLayoutManager(new LinearLayoutManager(this));
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchedText = searchtxt.getText().toString();
firebasesearch(searchedText);
}
});
}
private void firebasesearch(String searchtxt) {
Query firebaseSearchQuery=ref.orderByChild("jobTitle").startAt(searchtxt).endAt(searchtxt+"\uf8ff");
FirebaseRecyclerOptions<jobclass> options = new FirebaseRecyclerOptions.Builder<jobclass>().setQuery(firebaseSearchQuery, jobclass.class).build();
FirebaseRecyclerAdapter<jobclass, jobviewholder> recycleradaptor = new FirebaseRecyclerAdapter<jobclass, jobviewholder>(options) {
#Override
protected void onBindViewHolder(#NonNull jobviewholder holder, int position, #NonNull jobclass model) {
holder.setDetails(model.getJobTitle(), model.getCompany(), model.getPay(), model.getType(), model.getExperience(), model.getAge());
}
#NonNull
#Override
public jobviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listlayout, parent, false);
jobviewholder jv = new jobviewholder(v);
return jv;
}
};
result.setAdapter(recycleradaptor);
Toast.makeText(showjobs.this, "Searching", Toast.LENGTH_LONG).show();
}
/* #Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<jobclass> options = new FirebaseRecyclerOptions.Builder<jobclass>().setQuery(ref, jobclass.class).build();
Toast.makeText(showjobs.this, "Searching", Toast.LENGTH_LONG).show();
FirebaseRecyclerAdapter<jobclass, jobviewholder> recycleradaptor = new FirebaseRecyclerAdapter<jobclass, jobviewholder>(options) {
#Override
protected void onBindViewHolder(#NonNull jobviewholder holder, int position, #NonNull jobclass model) {
holder.setDetails(model.getJobTitle(), model.getCompany(), model.getPay(), model.getType(), model.getExperience(), model.getAge());
}
#NonNull
#Override
public jobviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listlayout, parent, false);
jobviewholder jv = new jobviewholder(v);
return jv;
}
};
result.setAdapter(recycleradaptor);
}*/
public class jobviewholder extends RecyclerView.ViewHolder {
View v;
public jobviewholder(View itemView){
super(itemView);
v=itemView;
}
public void setDetails(String jobn, String companyn, String pay, String Ag, String xreq, String jtyp){
TextView jobtitle=findViewById(R.id.jname);
TextView companyname=findViewById(R.id.cname);
TextView payment=findViewById(R.id.sal);
TextView age=findViewById(R.id.agereq);
TextView exprequired=findViewById(R.id.reqex);
TextView jobtype=findViewById(R.id.type);
jobtitle.setText(jobn);
companyname.setText(companyn);
payment.setText(pay);
age.setText(Ag);
exprequired.setText(xreq);
jobtype.setText(jtyp);
}
}
}
Thank you for your time. I hope someone can help me find the problem.
result.setAdapter(recycleradaptor);
Toast.makeText(showjobs.this, "Searching", Toast.LENGTH_LONG).show();
to this recycleradaptor you have to start listening as well.You have to do that in onStart()
So you can do
#Override
protected void onStart() {
super.onStart();
recycleradaptor.startListening();
}
this is the working code for search using Firebase database`
private void searchFriend(String text_search) {
Query query = FirebaseDatabase.getInstance().getReference(Common.USERS)
.orderByChild("name")
.startAt(text_search)
.endAt(text_search + "\uf8ff");
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.setLifecycleOwner(this)
.build();
searchAdapterQuery = new FirebaseRecyclerAdapter<User, UserViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final UserViewHolder holder, int position, #NonNull final User user) {
holder.userName.setText(user.getName());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.all_user_recycler_view_item, viewGroup, false);
return new UserViewHolder(itemView);
}
};
searchAdapterQuery.startListening();
recyclerView.setAdapter(searchAdapterQuery);
}`

Products are in the database, but not showing in Fragment in my android app

I am trying to learn android and I have this shopping list, using the Cloud Firestore database. When I want to add products in the database, it works (I can see them in Firebase), but when I want to display them, they don't show up..any ideas why? Thank you!
This is a part of the onCreateView() function in ShoppingListFragment:
rootRef = FirebaseFirestore.getInstance();
shoppingListProductsRef = rootRef.collection("products").document(shoppingListId).collection("shoppingListProducts");
RecyclerView recyclerView = shoppingListViewFragment.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
TextView emptyView = shoppingListViewFragment.findViewById(R.id.empty_view);
ProgressBar progressBar = shoppingListViewFragment.findViewById(R.id.progress_bar);
Query query = shoppingListProductsRef.whereEqualTo("izInShoppingList", izInShoppingList)
.orderBy("productName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<ProductModel> firestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder<ProductModel>()
.setQuery(query, ProductModel.class)
.build();
firestoreRecyclerAdapter =
new FirestoreRecyclerAdapter<ProductModel, ProductViewHolder>(firestoreRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, int position, #NonNull ProductModel model) {
holder.setProduct(getContext(), shoppingListViewFragment, userEmail, userName, shoppingListModel, model);
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
return new ProductViewHolder(view);
}
#Override
public void onDataChanged() {
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
if (getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return super.getItemCount();
}
};
recyclerView.setAdapter(firestoreRecyclerAdapter);
return shoppingListViewFragment;
}

Firebase - check if uid child values match in Posts node,if so then add all score values together and store in String variable

I want to check if there are uid child values are matching in the Posts node,if so then I want to add all the respective score values together and store in a String variable.
Below there is my firebase structure
this is my code... i want to get the total score to a string variable and set the text in here...."holder.score.setText(Score);"
private void DisplayAllUserScores() {
//do... TotalPicScore & PostImage
FirebaseRecyclerOptions<Leaderboard> options =
new FirebaseRecyclerOptions.Builder<Leaderboard>()
.setQuery(LikesRef, Leaderboard.class)
.build();
FirebaseRecyclerAdapter<Leaderboard, LeaderboardActivity.ScoresViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Leaderboard, LeaderboardActivity.ScoresViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final LeaderboardActivity.ScoresViewHolder holder, int position, #NonNull final Leaderboard model) {
final String scores_id = getRef(position).getKey();
PostsRef.child(scores_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
final String userName = dataSnapshot.child("fullname").getValue().toString();
final String Score = dataSnapshot.child("score").getValue().toString();
final String userprofileimage = dataSnapshot.child("profileimage").getValue().toString();
//GetUserInformation();
holder.leaderboardUsernames.setText(userName);
holder.score.setText(Score);
Picasso.get().load(userprofileimage).placeholder(R.drawable.profile).into(holder.leaderboardProfilepicture);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public LeaderboardActivity.ScoresViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_users_scores_layout, parent, false);
ScoresViewHolder viewHolder = new ScoresViewHolder(view);
return viewHolder;
}
};
ScoreList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
I hope you are looking for something similar to this
int scoreTotal=0;
Query myTopPostsQuery = databaseReference.child("Posts").orderByChild("uid").equalTo(userId);
myTopPostsQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue()!=null){
for(DataSnapshot snapshot:dataSnapshot.getChildren())
scoreTotal= scoreTotal+ (int) snapshot.child("score").getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to remove one item on my data base when I click on my "delete" button?

I'm new to android studio, and for my android application I'm use Firebase.
I want to remove one item from my database when I click on my button delete(btnDelete).
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query= FirebaseDatabase.getInstance()
.getReference().child("users").child(uid).child("foto");
public ViewHolder(#NonNull View itemView) {
super(itemView);
foto_root=itemView.findViewById(R.id.foto_root);
tvNameF=itemView.findViewById(R.id.tvNameF);
tvPhoneF=itemView.findViewById(R.id.tvPhoneF);
tvAdressF=itemView.findViewById(R.id.tvAdressF);
tvMailF=itemView.findViewById(R.id.tvMailF);
tvNoteF=itemView.findViewById(R.id.tvNoteF);
btnDelete=itemView.findViewById(R.id.btnDelete);
}
public void setTvNameF(String tvNameFs){
tvNameF.setText(tvNameFs);
}
public void setTvPhoneF(String tvPhoneFs){
tvPhoneF.setText(tvPhoneFs);
}
}
/*
get on dataBase
*/
private void fetch() {
FirebaseRecyclerOptions<Foto> options=
new FirebaseRecyclerOptions.Builder<Foto>().setQuery(query, snapshot -> new Foto(
snapshot.child("id").getKey(),
snapshot.child("name").getValue().toString(),
snapshot.child("phone").getValue().toString(),
snapshot.child("adress").getValue().toString(),
snapshot.child("email").getValue().toString(),
snapshot.child("note").getValue().toString())).build();
adapter = new FirebaseRecyclerAdapter<Foto, FotoActivity.ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_item,parent,false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder viewHolder, int i, #NonNull Foto foto) {
viewHolder.setTvNameF(foto.getNameF());
viewHolder.setTvPhoneF(foto.getPhoneF());
viewHolder.setTvAdressF(foto.getAdressF());
viewHolder.setTvMailF(foto.getEmailF());
viewHolder.setTvNoteF(foto.getNoteF());
viewHolder.btnDelete.setOnClickListener(v -> {
delete();
});
}
};
rvFoto.setAdapter(adapter);
}
private void delete() {
Toast.makeText(FotoActivity.this, "remove", Toast.LENGTH_SHORT).show();
}
private void viewRecyclerViewFoto() {
linearLayoutManager=new LinearLayoutManager(this);
rvFoto.setLayoutManager(linearLayoutManager);
rvFoto.setHasFixedSize(true);
}
}
// adapter class
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
private void setInfoFoto() {
DatabaseReference databaseReference=
FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("foto").push();
Map<String,Object> mapFoto=new HashMap<>();
mapFoto.put("id",databaseReference.getKey());
mapFoto.put("name",etNameF.getText().toString());
mapFoto.put("phone",etPhoneF.getText().toString());
mapFoto.put("adress",etAdressF.getText().toString());
mapFoto.put("email",etMailF.getText().toString());
mapFoto.put("note",etNoteF.getText().toString());
databaseReference.setValue(mapFoto);
}
I want remove one item from foto and not all database.
Just use the following in your delete function, this will delete the value of "phone" node. You will need to know the uid of the user you want to delete otherwise you can replace it with a database node reference but then that will delete phone from all the user ids. Basically you will listen to the foto node, get all the push ids and loop through the push ids to remove the desired node.
Declare The Variables
private static final String TAG = "TestActivity";
private DatabaseReference fbDbRef;
OnCreate
final String uid = "youruid";
fbDbRef = FirebaseDatabase.getInstance().getReference().child("users")
.child(uid).child("foto");
Your Function
private void delete() {
fbDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String pushKey = snapshot.getKey();
Log.d(TAG, "pushKey: " + pushKey);
fbDbRef.child(pushKey).child("phone").removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

How to update Datamodel in RecyclerviewAdapter

i created a recyclerview where i can see all my chats. Every item contains the name, the lastmessage and a thumb. if the user send or receive a new message, it should be displayed there and the item should go to position 0. Now i have the problem that the message is displayed, but the chat item goes only to the first position if the position was not 0 before. So if i receive two new messages its not working anymore because the data model is the same like before. So how can i fit my data model to the current position of every item. Currently my adapter looks like this:
private static final String TAG = "CustomAdapter";
private Context context;
private Activity mActivity;
private List<MatchesObject> matchesList;
private String currentUid;
public matchadapterino(Activity mActivity, ArrayList<MatchesObject> mDataSet) {
this.mActivity = mActivity;
this.matchesList = mDataSet;
}
// Create new views (invoked by the layout manager)
#Override
public matchadapterino.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.matchesitem, viewGroup, false);
return new matchadapterino.ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final matchadapterino.ViewHolder viewHolder, final int position) {
viewHolder.getMatchname().setText(matchesList.get(position).getUsername());
if (!matchesList.get(position).getProfileImageUrl().equals("default")) {
Picasso.with(mActivity).load(matchesList.get(position).getProfileImageUrl()).into(viewHolder.getMatchImage());
getLastMSG(matchesList.get(position).getUserId(), viewHolder.getLastMSG(), position);
viewHolder.getMatchImage().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mActivity, UserDetailView.class);
//
i.putExtra("userId", matchesList.get(position).getUserId());
mActivity.startActivity(i);
}
});
} else {
viewHolder.getMatchImage().setImageResource(R.mipmap.ic_launcher_round);
}
viewHolder.getForeground().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mActivity, Chat.class);
Bundle b = new Bundle();
b.putString("matchId", matchesList.get(position).getUserId());
i.putExtras(b);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return matchesList.size();
}
// Get element from your dataset at this position and replace the contents of the view
// with that element
public void removeItem(int position) {
matchesList.remove(matchesList.get(position));
notifyItemRemoved(position);
}
// Return the size of your dataset (invoked by the layout manager)
/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView matchname, lastMSG;
public ImageView matchImage;
private RelativeLayout foreground;
private RelativeLayout background;
public ViewHolder(View v) {
super(v);
currentUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
matchname = itemView.findViewById(R.id.matchname);
matchImage = itemView.findViewById(R.id.matchImages);
lastMSG = itemView.findViewById(R.id.lastmsg);
foreground = itemView.findViewById(R.id.foregroundmatch);
background = itemView.findViewById(R.id.backgroundmatch);
}
public RelativeLayout getForeground() {
return foreground;
}
public RelativeLayout getBackground() {
return background;
}
public TextView getLastMSG() {
return lastMSG;
}
public TextView getMatchname() {
return matchname;
}
public ImageView getMatchImage() {
return matchImage;
}
}
private void getLastMSG(final String userId, final TextView lastMSG, final int position) {
final String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("connections").child("matches").child(userId);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
notifyItemMoved(0, position);
Toast.makeText(mActivity, "position changed" + position, Toast.LENGTH_LONG).show();
if (dataSnapshot.child("lastMsgBy").getValue().toString().equals(userid)) {
lastMSG.setTextColor(Color.parseColor("#d2403a3a"));
String lastMsg = dataSnapshot.child("lastMsg").getValue().toString();
lastMSG.setText(lastMsg);
} else {
lastMSG.setTextColor(Color.parseColor("#000000"));
String lastMsg = dataSnapshot.child("lastMsg").getValue().toString();
lastMSG.setText(lastMsg);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Categories