Accessing a child within a child firebase - android

This is not a duplicate.
I am trying to access a child within a child in firebase and then putting that child into a recycler adapter. It won't show in the recycler adapter. There is a similar question on here to this but when implementing it, it still doesn't work.
Currently using an adapter, a messages object and a fragment.
Fragment Activity
private ArrayList<Messages> results = new ArrayList<>();
private void listenForChat() {
final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
.child("receivedMessages");
messageUrlDb = userDb.child("messageUrl");
messageUrlDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = "";
if (dataSnapshot.child("messageUrl").getValue() != null)
message = dataSnapshot.child("messageUrl").getValue().toString();
Messages obj = new Messages(message, name, image);
if (!results.contains(obj)) {
results.add(obj);
messagesList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
initializeDisplay();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolders> {
private List<Messages> mMessageList;
private List<UserObject> usersList;
private Context context;
private DisplayTextFragment displayTextFragment;
private String message;
public ChatAdapter(List<Messages> mMessageList, Context context) {
this.mMessageList = mMessageList;
this.context = context;
}
#Override
public ChatViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_layout, null);
ChatViewHolders rcv = new ChatViewHolders(v);
return rcv;
}
#Override
public void onBindViewHolder(final ChatViewHolders holder, int position) {
holder.messageText.setText(mMessageList.get(position).getMessage());
}
#Override
public int getItemCount() {
return mMessageList.size();
}
public class ChatViewHolders extends RecyclerView.ViewHolder {
public TextView messageText, timeSent, mName;
ImageView mProfile;
LinearLayout mLayout;
public ChatViewHolders(View view) {
super(view);
messageText = (TextView) view.findViewById(R.id.message_text);
mLayout = itemView.findViewById(R.id.layout);
}
}
}
I am trying access (messageUrl) users -> receivedMessages -> messageUrl. However as there is a key they I assume it doesn't as far as messagesUrl. For the recycler adapter it needs take in messagesUrl as a string and update accordingly but I just can't do it.
If any more code is needed I can post. Thank you.

This is how you're attaching your ValueEventListener:
final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
.child("receivedMessages");
messageUrlDb = userDb.child("messageUrl");
messageUrlDb.addValueEventListener(new ValueEventListener() {
If we take the path from this code, you're attaching the listener to /users/$uid/receivedMessages/messageUrl. This path doesn't exist in the data you showed, so your onDataChanged will get called with an empty snapshot.
If you want to read all messages for the user, you should attach your listener to /users/$uid/receivedMessages and parse the snapshot inside onDataChanged:
final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
.child("receivedMessages");
userDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userMessages: dataSnapshot.getChildren()) {
for (DataSnapshot messageSnapshot: userMessages.getChildren()) {
System.out.println(messageSnapshot.getKey()+": "+messageSnapshot.getChild("messageUrl").getValue(String.class));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This loops over the two level of child nodes you have under the user's receivedMessages node.

Related

How do I align ListView items based on a condition?

I am creating a chat program with Android Studio, and I am having trouble figuring out a way to show a list of messages that are left aligned for incoming messages and right aligned for outgoing messages. Right now, they are all left aligned.
What is the simplest way to left and right align text based on if the user id is the same as the current logged in user id? Below is what it looks like right now.
Current List View Sample
Assuming you are using Firebase for this app and getting the currently logged-in user details, you can make some changes to the Adapter class (MessageAdapter in this example).
Credits to numerous youtube videos and online resources that I used to do this in my app
Create chat_item_right.xml and chat_item_left.xml for 2 different users
Make some changes in the MessageAdapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
private FirebaseUser firebaseUser;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl) {
this.mContext = mContext;
this.mChat = mChat;
this.imageurl = imageurl;
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// Get the view type and create the right view
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
}
else {
view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
}
return new MyViewHolder(view);
}
// Method to get each chat message and show it
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Chat chat = mChat.get(position);
if (imageurl.equals("default")) {
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
}
else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
if (chat.getType().equals("text")) {
holder.show_message.setText(chat.getMessage());
}
else if (chat.getType().equals("image")) {
// Depends on your code here
Glide.with(mContext).load(chat.getMessage()).into(holder.image_message);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView show_message, txt_seen;
private ImageView profile_image, image_message;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
txt_seen = itemView.findViewById(R.id.txt_seen);
image_message = itemView.findViewById(R.id.image_message);
}
}
#Override
public int getItemViewType(int position) {
// If i'm the sender show message on right else show it on left
if (mChat.get(position).getSender().equals(firebaseUser.getUid())) {
return MSG_TYPE_RIGHT;
}
else {
return MSG_TYPE_LEFT;
}
}
}
Call this in your MessageActivity or Fragment class
private MessageAdapter messageAdapter;
private List<Chat> mChat;
private DatabaseReference reference;
private FirebaseUser firebaseUser;
private String userid;
. // All your relevant code here
.
.
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
// You should have stored the current user the moment you have logged in
// in SharedPrefs perhaps (or DataStore or etc) so that we can compare later
// during set view_item to left or right
// For e.g sending the userID as bundle from Login Page to MessageActivity
// intent = new Intent(this, MessageActivity.class);
// bundle.putString("userid", user);
userid = intent.getStringExtra("userid");
private void readMessages(final String myId, final String userid, final String imageurl) {
mChat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
// Add to chat list only messages between you and the sender
assert chat != null;
// The below code depends on your Chat object class
// So please modify accordingly
if (chat.getReceiver() != null && chat.getSender() != null) {
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myId)) {
mChat.add(chat);
}
}
}
// Create a new adapter and set it to our view
messageAdapter = new MessageAdapter(MessageActivity.this, mChat, imageurl);
recyclerView.setAdapter(messageAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// Call the function
readMessages(firebaseUser.getUid(), userid, user.getImageURL());

Why does the recyclerview data loads only when the button is clicked the second time

I am developing an app based on placement. I have used firebase realtime database for this. I am matching company name from the "Job Post" db and "Applied Candidate" db, so that only applied candidates detail for that particular company will be displayed. Everything is working fine but the issue is the recyclerview's data loads only when the button is clicked the second time.
public class AppliedCandidateActivity extends AppCompatActivity {
Toolbar toolbarAppliedcandidate;
RecyclerView rvAppliedCandidate;
List<appliedData> ls;
String compNameposted;
AppCandidateAdapter adapter;
DatabaseReference dbJobPost,dbAppliedCandidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applied_candidate);
toolbarAppliedcandidate = findViewById(R.id.toolbarAppliedcandidate);
rvAppliedCandidate = findViewById(R.id.rvAppliedCandidate);
setSupportActionBar(toolbarAppliedcandidate);
getSupportActionBar().setTitle("Applied Candidate");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rvAppliedCandidate.setHasFixedSize(true);
rvAppliedCandidate.setLayoutManager(new LinearLayoutManager(this));
ls = new ArrayList<>();
adapter = new AppCandidateAdapter(getApplicationContext(),ls);
rvAppliedCandidate.setAdapter(adapter);
getCompany();
matchCompanyName();
}
void getCompany()
{
//To retrieve company name
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren())
{
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
//Toast.makeText(getApplicationContext(),postJobData.getCompName(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
void matchCompanyName()
{
//To retrieve data of applied candidate for particular company
dbAppliedCandidate = FirebaseDatabase.getInstance().getReference("Applied Candidate");
dbAppliedCandidate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren())
{
for (DataSnapshot ds1 : ds.getChildren())
{
appliedData data = ds1.getValue(appliedData.class);
String compName = data.getCompName().toString();
//Toast.makeText(getApplicationContext(),compName,Toast.LENGTH_LONG).show();
if(compName.equals(compNameposted))
{
ls.add(data);
}
else if(ls.isEmpty()== true){
Toasty.info(AppliedCandidateActivity.this,"No One Applied Yet!!",Toast.LENGTH_LONG,true).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class AppCandidateAdapter extends RecyclerView.Adapter<AppCandidateAdapter.AppCandidateViewHolder>{
List<appliedData> appliedDataList;
Context context;
public AppCandidateAdapter(Context mcontext,List list){
this.context = mcontext;
this.appliedDataList = list;
}
#NonNull
#Override
public AppCandidateViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.applied_candidate_compside,parent,false);
return new AppCandidateViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AppCandidateViewHolder holder, int position) {
appliedData data = appliedDataList.get(position);
holder.tvCandidateName.setText(data.getName());
holder.tvCandidateAppliedPost.setText(data.getPosition());
holder.tvCandidateQual.setText(data.getQualification());
holder.tvCandidateSkills.setText(data.getSkills());
}
#Override
public int getItemCount() {
return appliedDataList.size();
}
class AppCandidateViewHolder extends RecyclerView.ViewHolder{
TextView tvCandidateName,tvCandidateAppliedPost,tvCandidateQual,tvCandidateSkills;
Button btnDeleteCandidate,btnSendMail;
public AppCandidateViewHolder(#NonNull View itemView) {
super(itemView);
tvCandidateName = itemView.findViewById(R.id.tvCandidateName);
tvCandidateAppliedPost = itemView.findViewById(R.id.tvCandidateAppliedPost);
tvCandidateQual = itemView.findViewById(R.id.tvCandidateQual);
tvCandidateSkills = itemView.findViewById(R.id.tvCandidateSkills);
btnDeleteCandidate = itemView.findViewById(R.id.btnDeleteCandidate);
btnSendMail = itemView.findViewById(R.id.btnSendMail);
}
}
}
}
Assuming your onDataChange does get called, successfully reads the PostJobData data from the snapshot, and adds it to ls, you're not telling Android that the list has changed. Only once you notify the adapter of the change, will it rerender the view.
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
}
adapter.notifyDataSetChanged(); // notify the adapter
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});

How to delete item from recyclerview programmatically? [duplicate]

This question already has an answer here:
Deleting row from recycler view and firebase
(1 answer)
Closed 3 years ago.
I want to remove an item from my recyclerview using an if condition
Here is my code for my adapter class. What I want to do is remove from displaying if its status is equal to unlive I'm retrieving the data from firebase
ArrayList<Adapter_Hotels> hotelsList;
Context context;
public Hotels_Adapter(ArrayList<Adapter_Hotels> list, Context context) {
this.hotelsList = list;
this.context = context;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.listview_layout, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int i) {
holder.hName.setText(hotelsList.get(i).getTitle());
holder.hAddress.setText(hotelsList.get(i).getProvince() + ", " + hotelsList.get(i).getCountry());
Picasso.get().load(hotelsList.get(i).getUrl_path()).fit().into(holder.hImage);
String status = hotelsList.get(i).getStatus();
if (status.equals("unlive")) {
removeItem(holder.getAdapterPosition());
}
}
#Override
public int getItemCount() {
return hotelsList.size();
}
public void removeItem(int position){
hotelsList.remove(position);
this.notifyItemRemoved(position);
}
My activity code
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot hotelsSnapshot : dataSnapshot.getChildren()) {
Adapter_Hotels hotels = hotelsSnapshot.getValue(Adapter_Hotels.class);
String hotel_status = hotels.getStatus();
String hotel_name = hotels.getTitle();
String hotel_image = hotels.getUrl_path();
String hotel_province = hotels.getProvince();
String hotel_country = hotels.getCountry();
String hn = hotels.setTitle(hotel_name);
String hi = hotels.setUrl_path(hotel_image);
String hp = hotels.setProvince(hotel_province);
String hc = hotels.setCountry(hotel_country);
String hs = hotels.setStatus(hotel_status);
hotelList.add(new Adapter_Hotels(hn, hi, hc, hp, hs));
Log.v("DSDS", String.valueOf(hotelList.size()));
dialog.dismiss();
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
hotelsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
hotelsAdapter = new Hotels_Adapter(hotelList, getContext());
mListview.setLayoutManager(new LinearLayoutManager(getContext()));
mListview.setAdapter(hotelsAdapter);
To remove, you can add this line
hotelList.remove(getAdapterPosition());
Perform the above code inside onLongClick() method in the ViewHolder class.
#Override
public boolean onLongClick(View view) {
//You can generate one list from which user can choose to delete.
hotelList.remove(getAdapterPosition());
return true;
}
Hi there ! why don't you remove the line of your list before pass that to the adapter ?
You can define function in your Activity to do this , and then pass the final list to your adapter

Cast arraylist in recyclerview firebase

I have an array of data which I am retrieving from firebase. I am using a recyclerview to display the data but my adapter is not working correctly.I tried adding the arraylist in the adapter but this is not working.
It is saying the adapter is not attached and I am having a blank activity.
Any help on this ?
Here are my details.
Modal Class
public class Order {
private String ProductId;
private String ProductName;
private String Quantity;
public Order() {
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public String getProductName() {
return ProductName;
}
public void setProductName(String productName) {
ProductName = productName;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public Order(String productId, String productName, String quantity) {
ProductId = productId;
ProductName = productName;
Quantity = quantity;
}
}
Adapter
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersViewHolder> {
List<Order> myfoods;
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
#NonNull
#Override
public AllOrdersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.allorders_layout,parent,false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull AllOrdersViewHolder holder, int position) {
holder.foodname.setText(myfoods.get(position).getProductName());
holder.foodquantity.setText(myfoods.get(position).getQuantity());
holder.foodId.setText(myfoods.get(position).getProductId());
}
#Override
public int getItemCount() {
return myfoods.size();
}
}
Test Class
public class Test extends AppCompatActivity {
FirebaseDatabase db;
DatabaseReference requests;
RecyclerView lstFoods;
RecyclerView.LayoutManager layoutManager;
TextView food_id,food_quan,food_name;
// List foods = new ArrayList<>();
// RecyclerView.Adapter<AllOrder> adapter;
// List<String> myOrders = new ArrayList<String>();
// ArrayList<String> foods=new ArrayList<>();
List<String> myfoods = new ArrayList<String>();
AllOrdersAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
loadOrderss();
}
private void loadOrderss() {
requests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
// List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
// String data = String.valueOf(postSnapshot.getValue(Order.class));
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
// myfoods.add(String.valueOf(Order.class));
System.out.println("Gained data: " + ing.child("productName").getValue(String.class));
}
}
}
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles.
In your Adapter you have:
List<Order> myfoods;
and
public AllOrdersAdapter(List<Order> myfoods) {
this.myfoods = myfoods;
}
but in your activity code you pass:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
one is a ArrayList of String the other of Order !
You also need to change your adapter class to something like:
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> {
private static final String TAG = AllOrdersAdapter.class.getSimpleName();
private ArrayList<Order> mData;
public class AllOrdersViewHolder extends RecyclerView.ViewHolder {
public TextView mTvFoodname;
public TextView mTvFoodQuantity;
public TextView mTvFoodId;
public AllOrdersViewHolder(View v){
super(v);
// TODO: You need to assign the appropriate View Id's instead of the placeholders ????
mTvFoodQuantity = v.findViewById(R.id.????);
mTvFoodname = v.findViewById(R.id.????);
mTvFoodId = v.findViewById(R.id.????);
}
}
public AllOrdersAdapter(ArrayList<Order> data){
this.mData = data;
}
#Override
public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false);
return new AllOrdersViewHolder(itemView);
}
#Override
public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){
//TODO: You need to decide whether you want to pass a string or order object
Order data = mData.get(position);
final String name = data.getProductName();
final String quantity = data.getQuantity();
final String id = data.getProductId();
holder.mTvFoodname.setText(name);
holder.mTvFoodQuantity.setText(quantity );
holder.mTvFoodId.setText(id)
}
#Override
public int getItemCount(){
return mData.size();
}
}
Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method.
You should also follow the advice given by Frank.
EDIT
Change your onDataChange() method to this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
if (postSnapshot.getValue() != null) {
List ingredients = new ArrayList<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
String name = ing.child("productName").getValue(String.class);
String quantity = ing.child("quantity").getValue(String.class);
String productId = ing.child("productId").getValue(String.class);
// Using your overloaded class constructor to populate the Order data
Order order = new Order(productId, name, quantity);
// here we are adding the order to the ArrayList
myfoods.add(order);
Log.e(TAG, "Gained data: " + name)
}
}
}
adapter.notifyDataSetChanged();
}
In your Activity you will need to change the ArrayList class variable "myfoods" to this:
ArrayList(Order) myfoods = new ArrayList<>();
and in your onCreate() method you can now change:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
to simply this:
adapter = new AllOrdersAdapter(myfoods);
Also notice that I have made some changes in my original code above.
You'll want to create the adapter, and attach it to the view, straight in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
//firebase
db = FirebaseDatabase.getInstance();
requests= db.getReference().child("Requests");
lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
lstFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstFoods.setLayoutManager(layoutManager);
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
lstFoods.setAdapter(adapter);
loadOrders();
}
This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like:
ArrayList<String> myfoods = new ArrayList<String>();
Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view):
private void loadOrders() {
requests.child("foods").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ing: postSnapshot.getChildren()) {
myfoods.add(ing.child("quantity").getValue(String.class));
myfoods.add(ing.child("productName").getValue(String.class));
myfoods.add(ing.child("productId").getValue(String.class));
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}

How to get Particular Child nodes in Fire base android?

i need to get bestseller values from AGS Biryani in recyler view , No idea about how to add the child values to the recyler adapter based on parent node
Model
public class Food_List {
private String itemname;
private String itemdescrp;
private long itemnewprice;
private long itemoldprice;
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getItemdescrp() {
return itemdescrp;
}
public void setItemdescrp(String itemdescrp) {
this.itemdescrp = itemdescrp;
}
public long getItemnewprice() {
return itemnewprice;
}
public void setItemnewprice(long itemnewprice) {
this.itemnewprice = itemnewprice;
}
public long getItemoldprice() {
return itemoldprice;
}
public void setItemoldprice(long itemoldprice) {
this.itemoldprice = itemoldprice;
}
}
Food_List_ViewHolders
ViewHolders to add the value in Recyler view
public class Food_List_ViewHolders extends RecyclerView.ViewHolder {
View mView;
private Context context;
Context mContext;
String nodata;
public Food_List_ViewHolders(View itemView) {
super(itemView);
mView=itemView;
}
#SuppressLint("SetTextI18n")
public void setDetails(Context applicationContext, final String itemname, String itemdescrp,
final long itemnewprice,
final long itemoldprice
)
{
final TextView dishitemname=mView.findViewById(R.id.dishheader);
TextView dishitemnamedescrp=mView.findViewById(R.id.dishheaderdescrp);
TextView dishitemnameoldprice=mView.findViewById(R.id.itemoldprice);
TextView dishitemnamenewprice=mView.findViewById(R.id.itemnewprice);
dishitemname.setText(itemname);
dishitemnamedescrp.setText(itemdescrp);
dishitemnamenewprice.setText(applicationContext.getString(R.string.Rup) + itemnewprice);
dishitemnameoldprice.setText(applicationContext.getString(R.string.Rup) + itemoldprice);
mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View mView) {
Context context = mView.getContext();
}
});
}
}
Main Activity
Don't Know how to add Child values in DataSnapshot
mRecycleriew =findViewById(R.id.my_recycler_views);
mRecycleriew.setLayoutManager(new LinearLayoutManager(this));
mFirebaseDatabase= FirebaseDatabase.getInstance();
mRef=mFirebaseDatabase.getReference().child("restaurants").equalTo("AGS Biryani");
//DatabaseReference restaurantsRef = mRef.child("restaurants");
mRef(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
progressDoalog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void mRef(ValueEventListener valueEventListener) {
}
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Food_List,Food_List_ViewHolders> firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<Food_List, Food_List_ViewHolders>(
Food_List.class,
R.layout.item_child,
Food_List_ViewHolders.class,
mRef)
{
#Override
protected void populateViewHolder(Food_List_ViewHolders viewHolder, Food_List model, int position) {
viewHolder.setDetails(getApplicationContext(),model.getItemname(),model.getItemdescrp(),model.getItemnewprice(),model.getItemoldprice());
}
};
mRecycleriew.setAdapter(firebaseRecyclerAdapter);
}
Essentially you're doing:
mRef=mFirebaseDatabase.getReference().child("restaurants").equalTo("AGS Biryani");
FirebaseRecyclerAdapter<Food_List,Food_List_ViewHolders> firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<Food_List, Food_List_ViewHolders>(
Food_List.class,
R.layout.item_child,
Food_List_ViewHolders.class,
mRef)
Which means that you're showing all restaurants with a priority of AGS Biryani. That's not what you're trying to do, so you'll need to modify your ref:
mRef=mFirebaseDatabase.getReference().child("restaurants/AGS Biryani/bestsellers");
When you pass this ref into the FirebaseRecyclerAdapter, it will show all bestsellers for AGS Biryani.

Categories

Resources