List in Recycle view is more then displayed data - android

List all information of both service providers (Babysitter and Kids event planner) from the Account class
public class Register_Requests extends Fragment {
FirebaseAuth mAuth;
DatabaseReference refAccount,searchdatabase;
FirebaseUser user;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
RecyclerView recyclerView;
Adapter adapter;
TextView Fullname_Admin;
Button btnlogOutAdmin,search_bar;
String F_name, L_name;
ArrayList<Account> list = new ArrayList();
private String mParam1;
private String mParam2;
public Register_Requests() { }
public static Register_Requests newInstance(String param1, String param2) {
Register_Requests fragment = new Register_Requests();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);}}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_register__requests, container, false);
ImageView imgfake;
TextView nametext,SPtext,count;
imgfake=view.findViewById(R.id.imgfake);
nametext=view.findViewById(R.id.nametext);
SPtext=view.findViewById(R.id.SPtext);
count= (TextView) view.findViewById(R.id.counttext);
btnlogOutAdmin = view.findViewById(R.id.signout_admin);
Fullname_Admin= (TextView) view.findViewById(R.id.name_admin);
recyclerView =(RecyclerView)view.findViewById(R.id.recview_SP);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
user= FirebaseAuth.getInstance().getCurrentUser();
refAccount = FirebaseDatabase.getInstance().getReference().child("Account");
String Id_admin = FirebaseAuth.getInstance().getCurrentUser().getUid();
// Welcome admin
FirebaseDatabase.getInstance().getReference("Admin").child(Id_admin)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Admin admin_display = snapshot.getValue(Admin.class);
if(admin_display != null){
F_name = admin_display.getA_FullName();
L_name = admin_display.getA_LastName();
Fullname_Admin.setText("Welcome "+F_name+" "+L_name+" !");}}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(),"Something Wrong Happened",Toast.LENGTH_SHORT).show();}});
// Logout admin
btnlogOutAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
perfrences.clearData(getActivity());
getActivity().finish();
startActivity(new Intent(getActivity(),Login.class));}});
// List Babysitter and Kids Event Planner from Account
refAccount.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
if (snapshot.exists())
{
for (DataSnapshot snapshot1: snapshot.getChildren())
{
Account a=snapshot1.getValue(Account.class);
list.add(a);
}
adapter.notifyDataSetChanged();
count.setText(adapter.getItemCount()+" Registers"); }
else
{ nametext.setText("No Available Service Providers");
nametext.setVisibility(View.VISIBLE);} }
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
// Adapter for recycle view
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(refAccount, Account.class)
.build();
adapter = new Adapter(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}}
Adapter class where I'll get access from Account class to both service provider
public class Adapter extends FirebaseRecyclerAdapter<Account, Adapter.viewHolder> {
DatabaseReference Ref,Ref2,check;
boolean flag =true, flag2=true;
String userIDs,total_count,IDsitter,IDplanner;
public Adapter(#NonNull FirebaseRecyclerOptions<Account> options) { super(options); }
#Override
protected void onBindViewHolder(#NonNull viewHolder holder, int position, #NonNull Account model) {
Ref= FirebaseDatabase.getInstance().getReference("Babysitter");
Ref2= FirebaseDatabase.getInstance().getReference("Kids Event Planner");
userIDs = model.user_id;
// Print all the Babysitter
Ref.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
if(snapshot.hasChild("b_FirstName")){
String Fname = snapshot.child("b_FirstName").getValue().toString();
String Lname = snapshot.child("b_LastName").getValue().toString();
String photo = snapshot.child("b_Photo").getValue().toString();
String gender = snapshot.child("b_Gender").getValue().toString();
String nationality = snapshot.child("b_Nationality").getValue().toString();
String phone = snapshot.child("b_Phone").getValue().toString();
String B_date = snapshot.child("b_BirthDate").getValue().toString();
int Y_e = parseInt(snapshot.child("years_of_Experience").getValue().toString());
String exp= Integer.toString(Y_e);
String state= snapshot.child("registration_Status").getValue().toString();
String educate= snapshot.child("b_EducationLevel").getValue().toString();
holder.nametext.setText(Fname +" "+ Lname );
holder.SPtext.setText(model.getAccount_role());
Picasso.with(holder.imgfake.getContext()).load(photo).placeholder(R.drawable.ic_action_name).into(holder.imgfake);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity=(AppCompatActivity)view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, new eachInfo_SP(model.user_id,Fname,Lname,photo,
gender,nationality,phone,B_date,model.getAccount_email(),model.getAccount_role(), exp,state,educate)).addToBackStack(null).commit();}});}
else { flag=false;System.out.println("No values");} if (!(model.account_role.equals("Admin"))&& !(model.account_role.equals("Parent")) ){
// Log.e(String.valueOf(snapshot.getKey().equals(userIDs)), snapshot.getChildrenCount() + " Registers");
total_count = snapshot.getChildrenCount() + " Registers";
System.out.println(total_count);
}}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}});
// Print all the KEP
Ref2.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
KidsEventPlanner k= snapshot.getValue(KidsEventPlanner.class);
if(snapshot.hasChild("e_FirstName")){
String Fname = snapshot.child("e_FirstName").getValue().toString();
String Lname = snapshot.child("e_LastName").getValue().toString();
String photo = snapshot.child("e_Photo").getValue().toString();
String gender = snapshot.child("e_Gender").getValue().toString();
String nationality = snapshot.child("e_Nationality").getValue().toString();
String phone = snapshot.child("e_Phone").getValue().toString();
String B_date = snapshot.child("e_BirthDate").getValue().toString();
int Y_e = parseInt(snapshot.child("years_of_experience").getValue().toString());
String exp= Integer.toString(Y_e);
String state= snapshot.child("registration_status").getValue().toString();
String educate= snapshot.child("e_EducationLevel").getValue().toString();
holder.nametext.setText(Fname +" "+ Lname );
holder.SPtext.setText(model.getAccount_role());
Picasso.with(holder.imgfake.getContext()).load(photo).placeholder(R.drawable.ic_action_name).into(holder.imgfake);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity=(AppCompatActivity)view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, new eachInfo_SP(model.user_id,Fname,Lname,photo,
gender,nationality,phone,B_date,model.getAccount_email(),model.getAccount_role(), exp, state,educate)).addToBackStack(null).commit();}});}
else{flag2 = false; System.out.println("False");}} }
#Override
public void onCancelled(#NonNull DatabaseError error) {}});
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdata,parent,false);
viewHolder viewHolder = new viewHolder(view);
return viewHolder;}
public class viewHolder extends RecyclerView.ViewHolder
{
ImageView imgfake;
TextView nametext,SPtext,count;
public viewHolder(#NonNull View itemView) {
super(itemView);
imgfake=itemView.findViewById(R.id.imgfake);
nametext=itemView.findViewById(R.id.nametext);
SPtext=itemView.findViewById(R.id.SPtext);
count= (TextView) itemView.findViewById(R.id.counttext);}}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
This is the Account class where I'll save the user's ID. Basically, I have in this class 4 users and just wanted related information of service providers
public class Account {
String account_email,account_password ,account_role, user_id;
public Account() {}
public Account(String account_email, String account_password, String account_role, String user_id) {
this.account_email = account_email;
this.account_password = account_password;
this.account_role = account_role;
this.user_id = user_id;
}
public String getAccount_email() {return account_email;}
public void setAccount_email(String account_email) {this.account_email = account_email;}
public String getAccount_password() {return account_password;}
public void setAccount_password(String account_password) {this.account_password = account_password; }
public String getAccount_role() {return account_role;}
public void setAccount_role(String account_role) {this.account_role = account_role; }
public String getUser_id() { return user_id; }
public void setUser_id(String user_id) { this.user_id = user_id;}
}
As you can see in the account_role these are 3 users and the 4th is the parent
there are 16 nodes in the Account path
those are other paths of (Service providers) which is in total 8 nodes
The problem is I just invoked only the service provider's information which should display 8 items in recycle view but here is displaying the rest of the items in the account class which in total 16 items, which means 8 item's data is shown but the rest is empty and I want to display item list as the size of service providers. So How I can prevent this problem?
It's showing empty rows from the Account class.

To get only the child nodes from under /Account with a specific value for account_role, you can use a query to order and filter data:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Account");
Query query = ref.orderByChild("account_role").equalTo("Babysitter");
query. addListenerForSingleValueEvent(...
But you can only do this for a single value (like Babysitter above), or for a contiguous range of values (like: from Admin to Babysitter). There is no way to request (with a single query) a number of distinct values like you want.
Some options:
Perform a query (like I showed above) for each value, and then merge the results in your client-side code. The performance of this will be fine, but it will be a bit more code.
Give each child node a single property that exactly matches your condition, so for example: "Babysitter_or_KidsEventPlanner": true. Then you can filter on that property. This works best if you have a limited number of such combinations.
Perform a query on a range of values, for example: ref.orderByChild("account_role").startAt("Babysitter").endAt("Kids Event Planner"). Just keep in mind that this returns all nodes where the account_role value is between Babysitter and Kids Event Planner, so it'd also include nodes with Car mechanic. Sometimes this is a good option though, especially if you can order/rename the values in a way to allow your query needs.

Related

FirebaseRecyclerAdapter model returning null values

I'm trying to make a comment system for posts on my social media app. In my database each post has a section inside of "comments" table, like so:
"hypno--######" is the title of the social media post. It Contains the comment, user id of the user who posted the comment, and a unixtimestamp when the comment was posted. Each comment is titled after the time it was posted.
This is the Comment class
public class comment {
public String uID;
public String comment_t;
public long unixTimestamp;
public comment() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public comment(String uID, String comment_t, long unixTimestamp) {
this.uID = uID;
this.comment_t = comment_t;
this.unixTimestamp = unixTimestamp;
}
public String getuID() {
return uID;
}
public void setuID(String uID) {
this.uID = uID;
}
public String getComment() {return comment_t;}
public void setComment() {this.comment_t = comment_t; }
public long getUnixTimestamp() {
return unixTimestamp;
}
}
This is the Comment Adapter:
Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {
private DatabaseReference mDatabase;
private static final String TAG = "RecyclerViewAdapter";
private Context mContext;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private static AppCompatActivity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (AppCompatActivity) context;
}
public Adapter_Comment(#NonNull FirebaseRecyclerOptions<comment> options) {
super(options);
//this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder_com onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
return new ViewHolder_com(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder_com holder, int position, #NonNull comment model) {
mDatabase = FirebaseDatabase.getInstance().getReference();
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
holder.postPfp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//AppCompatActivity activity = (AppCompatActivity) v.getContext();
AppCompatActivity activity = unwrap(v.getContext());
Fragment OtherProfileFragment = new OtherProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("key", model.getuID());
OtherProfileFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
}
});
}
public class ViewHolder_com extends RecyclerView.ViewHolder {
TextView comment_text;
CircleImageView postPfp;
TextView time;
RelativeLayout comment_layout;
public ViewHolder_com(#NonNull View itemView) {
super(itemView);
postPfp = itemView.findViewById(R.id.iv_comment_icon);
comment_text = itemView.findViewById(R.id.tv_comment_text);
time = itemView.findViewById(R.id.tv_comment_time);
comment_layout = itemView.findViewById(R.id.comment_layout);
}
}
}
This is Comment Fragment:
public class CommentFragment extends Fragment {
private DatabaseReference mDatabase;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
View view;
String value;
RecyclerView recyclerView;
Query query;
TextView comment_text;
long unixTime = System.currentTimeMillis() / 1000L;
public long globalUnix;
Button comment_post;
String comment_string;
Adapter_Comment adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_comment, container, false);
value = getArguments().getString("key");
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.recyclerv_comment);
comment_text = view.findViewById(R.id.tv_comment_type);
comment_post = view.findViewById(R.id.btn_comment_post);
globalUnix = (unixTime * -1);
comment_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(comment_text.getText().toString() == NULL){
Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
}
else{
comment com = new comment();
com.uID = user.getUid();
com.comment_t = comment_text.getText().toString();
com.unixTimestamp = globalUnix;
mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);
}
}
});
initRecyclerView();
return view;
}
private void initRecyclerView(){
//Log.d(TAG, "initRecyclerView: init recyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();
FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();
adapter = new Adapter_Comment(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Inside of the adapter I'm using the comment model, to get the uID, comment and timestamp to fill the holder, however when i set these values im getting null values. Is there something im missing when trying to connect the adapter/firebase and model/holder?
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
There's really too much going on in here, but...
As far as I can see you're creating a FirebaseUI adapter on FirebaseDatabase.getInstance().getReference().child("comments"). FirebaseUI adapters show the direct child nodes of the node you pass in, so in your case it'll create one view for the hypno---...196 node. You're trying to read a Comment object from there, but don't exist until one level lower in your JSON.
So you can:
Either show the comments for one post, by basing the adapter off of that. So: FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196") (which the real key in there).
Or you can show one piece of information about each post, for example its key.
If you want to show a flat list of comments for all posts through the FirebaseUI adapter, you'll have to store a flat list of comments across all posts in your database too.

Dynamic Expandable Recyclerview List Failing

I'm new to Android and I know this might be a piece of cake but I'm struggling.
I was trying to create a dynamic expandable recycler view using firebase realtime database but the data is not displaying properly.
I'm passing a string from one activity to another and comparing the string to the database field and then displaying it's child components but I don't know where I'm failing.
I want to display the Parent and child field by comparing the name field with the value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_detail);
//string value from another activity
String value = getIntent().getExtras().getString("name");
recycler_view = (RecyclerView) findViewById(R.id.recycler_expand);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentReference = database.getReference().child("Tutors");
//comparing
parentReference.equalTo(value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ParentList> Parent = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String ParentKey = snapshot.getKey().toString();
snapshot.child("title").getValue();
DatabaseReference childReference =
FirebaseDatabase.getInstance().getReference().child(ParentKey);
childReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChildList> Child = new ArrayList<>();
for (DataSnapshot snapshot1:dataSnapshot.getChildren())
{
final String ChildValue = snapshot1.getValue().toString();
snapshot1.child("title").getValue();
Child.add(new ChildList(ChildValue));
}
Parent.add(new ParentList(ParentKey, Child));
DocExpandableRecyclerAdapter adapter = new DocExpandableRecyclerAdapter(Parent);
recycler_view.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database Structure
ChildList.java
public class ChildList implements Parcelable {
private String title;
public ChildList(String title) {
this.title = title;
}
protected ChildList(Parcel in) {
title = in.readString();
}
public static final Creator<ChildList> CREATOR = new Creator<ChildList>() {
#Override
public ChildList createFromParcel(Parcel in) {
return new ChildList(in);
}
#Override
public ChildList[] newArray(int size) {
return new ChildList[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String Title) {
this.title = Title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
}
Please anyone help me with this :(
Don't use equalTo().
Try this:
DatabaseReference parentReference = database.getReference().child("Tutors");
parentReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String NameKey = snapshot.getKey().toString();
if(value.equals(NameKey)){
//DO WHATEVER YOU WANT
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to get the correct table to fetch profile image for each user in firbase tables

Can anyone help me here I am confused as I have tried many example but I am getting always getting it wrong I guess firebase is not beginners friendly, what I am trying to achieve is getting a profile image from my table called Users and fetch the profile image using Glide or Picasso, inside this users table I have Username, Password, email, profilePic, userIds, my profile image url is saved on profilePic child table on User registration, I have tried some code but it is giving a null. Here is what I have tried.
String url = dataSnapshot.child(Common.currentUser.getUserName() +"/"+ "profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
This worked on fetching image but its only showing profile images on currentUserr so all image holder have same image, also I have tried this first which is fetching the url manually.
String url="https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";//Retrieved url as mentioned above
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
and also with this code
String url = dataSnapshot.child(users.child("/")+ "/profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
I am getting the path is correct I gess but still getting error like this
Invalid Firebase Database path: https://learnbravanese.firebaseio.com/Users/mo/profilePic. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
can someone help me please how to get each image for its user and show it on this fragment?
here is my full fragment.
public class RankingFragment extends Fragment {
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl,imageTable;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
DataSnapshot dataSnapshot;
private Context context;
String Storage_Path = "All_Image_Uploads/";
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
private FirebaseAuth mAuth;
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
imageTable = database.getReference("DefaultImages");
storageReference = FirebaseStorage.getInstance().getReference("All_Image_Uploads/");
users = FirebaseDatabase.getInstance().getReference("Users");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
// storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference().child("Users");
final String pathtobackimage;
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(final RankingViewHolder viewHolder, final Ranking model, int position) {
// StorageReference backref = storageReference.child("All_Image_Uploads/1584768076891.jpg");
// FirebaseUser firebaseUser = mAuth.getCurrentUser();
ImageView imageView;
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
// String url = "https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";
;
//users = FirebaseDatabase.getInstance().getReference().child("Users").child(model.getUserName());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//String imageUrl = dataSnapshot.child("profilePic").getValue().toString();
String url = dataSnapshot.child(Common.currentUser.getUserName() +"/"+ "profilePic").getValue().toString();
// String url="https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";//Retrieved url as mentioned above
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
// String link =dataSnapshot.child("profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
// Picasso.with(getContext()).load(dataSnapshot.child("profilePic").getValue(User_Info.class).toString())
// .into(viewHolder.profileImageView);
// Glide.with(getContext()).load(users.child(model.getUserName() +"/"+ "profilePic"))
// .into(viewHolder.profileImageView);
// Glide.with(getContext()).load(model.getImage()).into(viewHolder.profileImageView);
// Glide.with(getContext()).load(model.getUrlProfilePic())
// .into(viewHolder.profileImageView);
// Glide.with(viewHolder.profileImageView.getContext()).load(model.getProfilepic()).into(viewHolder.profileImageView);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum,userName,userName);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
After few tries I have managed to fix the null issue by trying this code, I was calling for a wrong Firebase table I am guessing.
#Override
protected void populateViewHolder(final RankingViewHolder viewHolder, final Ranking model, int position) {
ImageView imageView;
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.with(getActivity()).load(dataSnapshot.child(model.getUserName()).child("profilePic").getValue().toString())
.into(viewHolder.profileImageView);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
I am only learning so I have no idea what else was wrong.

Chat Android - Firebase, synchronization delay problems

For months I have created a chat for the Android system using Firebase as a database.
I followed this guide here
( link ) and at the beginning it was all right, the chat was good and it didn't have any kind of delays. I then started to add other particularities, such as the display or not of the message and the status of the participants (online and offline) and from that moment three problems began to manifest in particular:
1) when I change the chat activity to go to another and then return to the chat, the layout appears empty without messages and if you try to change the activity the application closes itself. I found out that I get this error:
E/RecyclerView: No adapter attached; skipping layout
These are the files that make up the part related to chat:
MessageChat.java
public class MessageChat {
private String sender;
private String receiver;
private String msg;
private String currenttime;
private boolean isseen;
public MessageChat(String sender, String receiver, String msg, String currenttime, boolean isseen){
this.sender = sender;
this.receiver = receiver;
this.msg = msg;
this.currenttime = currenttime;
this.isseen = isseen;
}
public MessageChat(){}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {return receiver;}
public void setReceiver(String receiver) { this.receiver = receiver;}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCurrenttime() {
return currenttime;
}
public void setCurrenttime(String currenttime) {
this.currenttime = currenttime;
}
public boolean isIsseen() {return isseen;}
public void setIsseen(boolean isseen) {this.isseen = isseen;}
}
msgAdapter.java
public class msgAdapter extends RecyclerView.Adapter<msgAdapter.MsgViewHolder> {
public static final int INT_TYPE_LEFT = 0;
public static final int INT_TYPE_RIGHT = 1;
private static List<MessageChat> mChat;
private static Context context;
private FirebaseUser fuser;
public msgAdapter(List<MessageChat> msg, Context context) {
this.mChat = msg;
this.context = context;
}
#Override
public msgAdapter.MsgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == INT_TYPE_RIGHT) {
View view = LayoutInflater.from(context).inflate(R.layout.right_message, null);
msgAdapter.MsgViewHolder msgViewHolder = new msgAdapter.MsgViewHolder(view);
return msgViewHolder;
}else{
View view = LayoutInflater.from(context).inflate(R.layout.left_message, null);
msgAdapter.MsgViewHolder msgViewHolder = new msgAdapter.MsgViewHolder(view);
return msgViewHolder;
}
}
#Override
public void onBindViewHolder(final msgAdapter.MsgViewHolder holder, final int position) {
MessageChat msg = mChat.get(position);
holder.show_msg.setText(msg.getMsg());
if ((position == mChat.size()-1) && msg.getSender().equals(fuser.getUid())){
if (msg.isIsseen()){
holder.tv_seen.setText(" Seen ");
holder.tv_seen.setVisibility(View.VISIBLE);
}else {
holder.tv_seen.setText(" Sent ");
holder.tv_seen.setVisibility(View.VISIBLE);
}
}else{
holder.tv_seen.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public static class MsgViewHolder extends RecyclerView.ViewHolder {
TextView username, show_msg, tv_seen;
public MsgViewHolder(final View itemView) {
super(itemView);
show_msg = (TextView) itemView.findViewById(R.id.show_msg);
tv_seen = (TextView) itemView.findViewById(R.id.tv_seen);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// item clicked
MessageChat msg = mChat.get(getAdapterPosition());
String ctime = msg.getCurrenttime();
TastyToast.makeText(context, ctime, TastyToast.LENGTH_LONG, TastyToast.INFO);
}
});
}
}
#Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return INT_TYPE_RIGHT;
}else{
return INT_TYPE_LEFT;
}
}
}
On the internet I have found many answers that solve this problem in the following way, replacing this:
View view = LayoutInflater.from(context).inflate(R.layout.right_message, null);
to this:
View view = LayoutInflater.from(context).inflate(R.layout.right_message, parent, false);
But in my case I only got the busted chat with empty spaces between one comic and another.
Homefragment.java
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private View v;
private ImageButton btn_send;
private EditText et_send_mex;
private DatabaseReference reference;
private msgAdapter mAdapter;
private List<MessageChat> mChat;
private RecyclerView recyclerView;
private FirebaseUser user;
private String Uid, Oid;
private static final String sId = "xyz1";
private static final String pId = "xyz2";
ValueEventListener seenListener;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_home, container, false);
btn_send = v.findViewById(R.id.btn_send);
et_send_mex = v.findViewById(R.id.et_send_mex);
recyclerView = v.findViewById(R.id.rv_mex);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llManager = new LinearLayoutManager(getContext());
llManager.setStackFromEnd(true);
recyclerView.setLayoutManager(llManager);
user = FirebaseAuth.getInstance().getCurrentUser();
Uid = user.getUid();
btn_send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// notify = true;
String m = et_send_mex.getText().toString();
if (!m.equals("") || !m.equals("\n")){
if (Uid.equals(pId)){
sendMessage(Uid,sId,m);
}else if (Uid.equals(sId)){
sendMessage(Uid,pId,m);
}
}
}
});
readMessage();
return v;
}
private void seenMessage(final String senderId){
reference = FirebaseDatabase.getInstance().getReference("chats");
seenListener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
MessageChat msgchat = snapshot.getValue(MessageChat.class);
if (msgchat.getReceiver().equals(user.getUid()) && msgchat.getSender().equals(senderId)){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
month = month+1;
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int sec = c.get(Calendar.MINUTE);
String dt = day+" - "+month+" - "+year+", "+hour+":"+sec;
hashMap.put("currenttime", dt);
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("msg", message);
hashMap.put("isseen", false);
reference.child("chats").push().setValue(hashMap);
et_send_mex.setText("");
}
private void readMessage (){
mChat = new ArrayList<>();
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
MessageChat chat = snapshot.getValue(MessageChat.class);
mChat.add(chat);
if (!chat.getSender().equals(Uid)){
Oid = chat.getSender();
seenMessage(Oid);
}
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// user status
private void status(String status){
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(user.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
month = month+1;
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int sec = c.get(Calendar.MINUTE);
String dt = day+" - "+month+" - "+year+", "+hour+":"+sec;
hashMap.put("lastaccess", dt);
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
public void onResume() {
super.onResume();
status("online");
recyclerView.setAdapter(mAdapter);
}
#Override
public void onPause() {
super.onPause();
reference.removeEventListener(seenListener);
status("offline");
}
}
I was also advised to add in here:
#Override
public void onResume() {
super.onResume();
status("online");
}
The following code:
recyclerView.setAdapter(mAdapter);
But with poor results (maybe you can suggest me if it is right to add this part here or not, thank you very much)
2) When I send a message, it often takes a long time to reach the database, let's say that Firebase is not really a realtime database. Here I have not encountered any type of error, it is simply very slow.
3) Later I also added the change of state, simply when the application is closed or in background ( onPause () ), the state is set to offline in the database, otherwise it is online. But often it doesn't work properly, probably application crashes or delays affect this.
I remain available for any other part of the code or for clarification.
I thank you in advance for your help and I apologize for my bad English, I have been working on this application since last spring and I still have not been able to solve these problems.
first thing you want to do is, remove the part in your onCreate.
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
readMessage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here you basically put a reference on the database (chats) and every time it changes, it will call your function readMessage, which will always override your messages and put another listener on the same spot. Make sure you understand, that addValueEventListener is triggered every time the tree/path (chats) in firebase is updated!
You could simply replace the code from above with:
readMessage();
that would already make sure it is listening to your db. I believe that firebase is not slow, but that the two listeners maybe overriding their result.
About the next part i am not 100%, but i believe you can remove
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
from onDataChange (in readMessage) and put it directly under that part where you create the ArrayList. Like this:
mChat = new ArrayList<>();
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
reference = FirebaseDatabase.getInstance().getReference("chats");
I hope i understood your problem and my answer will give you a bit more clarity :)
Greetings!

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
}
});
}

Categories

Resources