Unable to retrieve data from firebase realtime database on to recyclerview [duplicate] - android

This question already has an answer here:
Error in fetching data from Firebase to RecyclerView. FATAL EXCEPTION: ... does not define a no-argument constructor
(1 answer)
Closed 2 years ago.
I am trying to retrieve data from firebase realtime database on to my recyclerview . Earlier i was able to retrieve data on to my recyclerview but don't know what happened it suddenly started showing me error.
I get error in this line
User user=snapshot.getValue(User.class);
And this error in logcat window
com.google.firebase.database.DatabaseException: Class com.shivam.chatapp2.Model.User does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize
My Full Code
UserAdapter.java:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
public UserAdapter(Context mContext, List<User> mUsers) {
this.mContext = mContext;
this.mUsers = mUsers;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.username);
profile_image=itemView.findViewById(R.id.profile_image);
}
}
}
User.java:
public class User {
private String id;
private String First;
private String Last;
private String EmailID;
public User(String id, String first, String last, String emailID) {
this.id = id;
First = first;
Last = last;
EmailID = emailID;
}
public User(String userid, String first_name, String eMail) {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getEmailID() {
return EmailID;
}
public void setEmailID(String emailID) {
EmailID = emailID;
}
}
UserFragment.java:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
public UsersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
readUser();
return view;
}
private void readUser() {
final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
User user=snapshot.getValue(User.class);
mUsers.add(user);
}
mUserAdapter=new UserAdapter(getContext(),mUsers);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

As per your error logs, it states that:
The User class doesnt has a default constructor with no parameters stated in the User.class file.
Add a default constructor to the User class in the User.class file like:
public User()
{
}

Related

Unable to Get Images to Display in Recycler View- Text is Sucessfully Displayed

Please see the following issue:
All User Profile Images are not successfully displaying in the RecyclerView.
Text view is successfully displaying in the RecyclerView.
I looked up other similar issues online, but have not been able to find a solution.
I have updated my google play services, and my Firebase storage dependencies.
I am able to successfully pull the current user profile image in another activity.
I am getting the following 404 error message below:
**Adapter**
public class FindFriendsAdapter extends RecyclerView.Adapter<FindFriendsAdapter.FindFriendsViewHolder>
{
private Context context;
private List<FindFriendModel> findFriendModelList;
////This is a constructor and is a must have for recyclerviews/////
public FindFriendsAdapter(Context context, List<FindFriendModel> findFriendModelList) {
this.context = context;
this.findFriendModelList = findFriendModelList;
}
////This is a constructor and is a must have for recyclerviews/////
#NonNull
#Override
public FindFriendsAdapter.FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.find_friends_layout, parent, false);
return new FindFriendsViewHolder(view); ///// layout converts our xml layout file to a programmable file some kind of way.
}
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
StorageReference fileref = FirebaseStorage.getInstance().getReference().child(Constants.IMAGES_FOLDER +"/" + friendModel.getProfileimage());
fileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(context)
.load(uri)
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
});
}
#Override
public int getItemCount() {
return findFriendModelList.size();
}
public class FindFriendsViewHolder extends RecyclerView.ViewHolder{
private CircleImageView imageView_profile;
private TextView text_view_full_name;
private ImageButton button_request, button_cancel_request;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
imageView_profile = itemView.findViewById(R.id.find_friends_profile_picture);
text_view_full_name = itemView.findViewById(R.id.find_friends_user_full_name);
button_request = itemView.findViewById(R.id.button_send_requests);
button_cancel_request = itemView.findViewById(R.id.button_cancel_requests);
}
}
}
**Model Class**
public class FindFriendModel
{
private String full_name;
private String profileimage;
private String userID;
private boolean requestSent;
public FindFriendModel(String full_name, String profileimage, String userID, boolean requestSent) {
this.full_name= full_name;
this.profileimage = profileimage;
this.userID = userID;
this.requestSent = requestSent;
}
public FindFriendModel() {}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public boolean isRequestSent() {
return requestSent;
}
public void setRequestSent(boolean requestSent) {
this.requestSent = requestSent;
}
}
**Fragment Java Class**
public class FindFriendsFragment extends Fragment {
private RecyclerView recycler_view_find_friends;
private FindFriendsAdapter findFriendsAdapter;
private List<FindFriendModel> findFriendModelList;
private TextView text_view_empty_Friends_List;
private DatabaseReference databaseReference;
private FirebaseUser currentUser;
public FindFriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_find_friends, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recycler_view_find_friends = view.findViewById(R.id.recycler_view_find_friends);
text_view_empty_Friends_List = view.findViewById(R.id.text_view_empty_find_friends);
recycler_view_find_friends.setLayoutManager(new LinearLayoutManager(getActivity()));
findFriendModelList = new ArrayList<>();
findFriendsAdapter = new FindFriendsAdapter(getActivity(), findFriendModelList);
recycler_view_find_friends.setAdapter(findFriendsAdapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
text_view_empty_Friends_List.setVisibility(View.VISIBLE);
Query query = databaseReference.orderByChild("full_name");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
findFriendModelList.clear();
for (final DataSnapshot ds : dataSnapshot.getChildren())
{
final String userID = ds.getKey();
if (userID.equals(currentUser.getUid()))
return;
if (ds.child("full_name").getValue()!=null)
{
String fullName = ds.child("full_name").getValue().toString();
String profileImage = ds.child("profileimage").getValue().toString();
findFriendModelList.add(new FindFriendModel(fullName, profileImage, userID, false));
findFriendsAdapter.notifyDataSetChanged();
text_view_empty_Friends_List.setVisibility(View.GONE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(),"Failed to fetch friends", Toast.LENGTH_SHORT).show();
}
});
}
}
````
ds.child("full_name").getValue()!=null should be replaced by
Objects.equals(ds.child("full_name"), null)
It worked for me when I had the same error, maybe it will help you as well !
Figured out the issue:
The issue was that I was already saving my images images to Firebase Storage, and I was trying to get the download url string again.
I fixed the following part of my adapter:
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
Glide.with(context)
.load(friendModel.getProfileimage())
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}

how to retrive a list from the firebase database

this is my db structure
I have a list of passenger and i want to retrive them from the firebase database if the passenger list contains more than one passenger then i want to get those data show in one textView. But everytime it generates 2 textView if there were two passenger. I want in all cases it shows all the data in just one TextView.
This is my model Class`
public class RetrieveTickets {
private String name;
private String age;
private String gender;
public RetrieveTickets() {
}
public RetrieveTickets(String name, String age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<HashMap<String,Object>> toList(){
List<HashMap<String,Object>> list=new ArrayList<>();
HashMap<String,Object> map=new HashMap<>();
map.put("name",getName());
map.put("age",getAge());
map.put("gender",getGender());
list.add(map);
return list;
}
}
this is MyActivity where i am showing the data
public class MyBookingsActivity extends AppCompatActivity{
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseAuth mAuth;
private FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder> firebaseRecyclerAdapter;
public static List<String> trips=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bookings);
recyclerView = (RecyclerView) findViewById(R.id.my_bookings);
recyclerView.setHasFixedSize(true);
String tripId = getIntent().getStringExtra("TripId");
trips.add(tripId);
// String bookingId = getIntent().getStringExtra("BookingId");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userId = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.child("BooKings").child(userId).child(tripId).child("passenger");
FirebaseRecyclerOptions<RetrieveTickets> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<RetrieveTickets>()
.setQuery(query, RetrieveTickets.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<RetrieveTickets, BookingHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull BookingHolder holder, int position, #NonNull RetrieveTickets model) {
holder.setPassengers(model);
}
#NonNull
#Override
public BookingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.tickets, parent, false);
return new BookingHolder(view);
}
#Override
public void onError(#NonNull DatabaseError error) {
super.onError(error);
Toast.makeText(MyBookingsActivity.this,"error"+error,Toast.LENGTH_LONG).show();
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null) {
firebaseRecyclerAdapter.stopListening();
}
}
public static class BookingHolder extends RecyclerView.ViewHolder{
private TextView passenger;
public BookingHolder(#NonNull View itemView) {
super(itemView);
passenger=(TextView)itemView.findViewById(R.id.passenger);
}
void setPassengers(RetrieveTickets retrieveTickets) {
passenger.setText(retrieveTickets.toList().toString());
}
}
If you want to display all passengers in one TextView then you shouldn't do like this... Right now you are using RecyclerView and it will make rows == number of passengers and its exactly why we use RecyclerView
If you want to show PassengerList in one textView do like this
StringBuilder passengerStrBuilder = new StringBuilder();
for (String details : yourList) {
passengerStrBuilder.append(details + "\n");
}
textView.setText(passengerStrBuilder.toString());
Here yourList is Passenger List

Retrieve Image and name from firebase database in recycler view [duplicate]

everyone, I was trying to make a music app, and for this, I Created a Horizontal RecyclerView in my HomeFragment and my horizontal RecyclerView is getting an image with artist name.
But after clicking I load another Activity. In my other activity, I was trying to load SongsData from firebase in a listView with RecyclerView.
But the problem is I am not getting data from Firebase and it is returning null data. I provided my code below and here is the screenshot of my Firebase database:- ScreenShot
My List Class:-
public class TestUploads
{
private String songName;
private String songImageUri;
private String songUrl;
private String artistName;
public TestUploads() {
}
public String getSongName() {
return songName;
}
public void setSongName(String SongName) {
this.songName = SongName;
}
public String getSongImageUri() {
return songImageUri;
}
public void setSongImageUri(String SongImageUri) {
this.songImageUri = SongImageUri;
}
public String getSongUrl() {
return songUrl;
}
public void setSongUrl(String SongUrl) {
this.songUrl = songUrl;
}
public TestUploads(String SongImageUri, String SongName, String SongUrl ) {
this.songName = SongName;
this.artistName = SongImageUri;
this.songUrl = SongUrl;
}
}
My Adapter Class:-
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestViewHolder>{
private Context mContext;
private List<TestUploads> mUploads;
public TestAdapter(Context context , List<TestUploads> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public TestViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.test_package_layout , parent ,false);
return new TestViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TestViewHolder holder, int position) {
TestUploads uploadcurrent = mUploads.get(position);
holder.name.setText(uploadcurrent.getSongName());
Glide.with(mContext)
.load(uploadcurrent.getSongImageUri())
.into(holder.image_view);
}
#Override
public int getItemCount() {
return mUploads
.size();
}
public class TestViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView artist_name;
public CircleImageView image_view;
public TestViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.test_package_song_name);
artist_name = itemView.findViewById(R.id.test_package_artist_name);
image_view = itemView.findViewById(R.id.test_package_image_name);
}
}
}
My Activity:-
public class TestActivity extends AppCompatActivity {
private ValueEventListener listener;
private DatabaseReference reference;
private List<TestUploads> mUploads;
private RecyclerView mRecyclerView;
private TestAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_package_activity);
reference = FirebaseDatabase.getInstance().getReference("ArtistView").child(getIntent().getStringExtra("Artist"))
.child("Songs");
Toast.makeText(this, "" + getIntent().getStringExtra("Artist"), Toast.LENGTH_SHORT).show();
mUploads = new ArrayList<>();
mRecyclerView = findViewById(R.id.test_pacakge_recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.smoothScrollToPosition(0);
adapter = new TestAdapter(this , mUploads);
mRecyclerView.setAdapter(adapter);
listener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
TestUploads uploads =postSnapshot.getValue(TestUploads.class);
mUploads.add(uploads);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Sorry for so much code but this is not hard to solve. If you find the solution please reply to me. Thanks for reading this.
The problem in your code lies in the fact that the names of the fields in your TestUploads class are different than the name of the properties in your database. You have in your TestUploads class a field named songName but in your database, I see it as SongName and this is not correct. The names must match. When you are using a getter named getSongName(), Firebase is looking in the database for a field named songName and not SongName. See the lowercase s letter vs. capital letter S?
There are two ways in which you can solve this problem. The first one would be to remove the data in your database and add it again using field names that start with lowercase, as exist in your TestUploads class.
If you are not allowed to use the first solution, then the second approach will be to use annotations. So you should use the PropertyName annotation in front of the getters. So in your TestUploads class, a getter should look like this:
#PropertyName("SongName")
public String getSongName() {
return songName;
}

Unable to retrieve firestore database using recyclerView

I am using recyclerView and Adapter to fetch the data in profileActivity
here is my
public class studentDetailsRecyclerActivity extends AppCompatActivity {
//recyclerview to set the details for UI in the student profile activity
private RecyclerView mRecyclerView;
private storeDetailsAdapter mStoreDetailsAdapter;
private List<storeStudentDetails> studentDetailsList;
private FirebaseFirestore dbReference;
private ProgressBar mProgressBar;
private String TAG = studentDetailsRecyclerActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
dbReference = FirebaseFirestore.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_details);
mProgressBar = findViewById(R.id.progressbar);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView_products);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
studentDetailsList = new ArrayList<>();
mStoreDetailsAdapter = new storeDetailsAdapter(this,studentDetailsList);
mRecyclerView.setAdapter(mStoreDetailsAdapter);
//to get the "details" this is our collection from firestore so we must fetch them
//by calling the addOnSuccessListener
dbReference.collection("details").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) { //we must have to hide the progress bar when the data gets loaded
//here queryDocumentsSnapshot will hold all the "details" which is your collection in firestore
if(!queryDocumentSnapshots.isEmpty()){
//we must have to create empty list so that to store all
//details from DocumentsSnapshots
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
//enhanced for loop because we have to give every index documentSnapShot
for(DocumentSnapshot d: list){
storeStudentDetails sd = d.toObject(storeStudentDetails.class);
studentDetailsList.add(sd);
Log.d(TAG, "onSuccess: " + sd.toString());
}
//to refresh and sync we must have to use notifyDataSetChanged
mStoreDetailsAdapter.notifyDataSetChanged();
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
}
and here is my storeDetailsAdapter
import java.util.List;
public class storeDetailsAdapter extends RecyclerView.Adapter<storeDetailsAdapter.StudentViewHolder>{
private Context context;
private List<storeStudentDetails> studentDetailsList;
public storeDetailsAdapter(Context context, List<storeStudentDetails> studentDetailsList) {
this.context = context;
this.studentDetailsList = studentDetailsList;
}
#NonNull
#Override
public StudentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new StudentViewHolder(
LayoutInflater.from(context).inflate(R.layout.profile_activity, parent, false)
);
}
#Override
public void onBindViewHolder(#NonNull StudentViewHolder holder, int position) {
storeStudentDetails mStoreDetails = studentDetailsList.get(position);
holder.studName.setText(mStoreDetails.getStudentName());
holder.rollNum.setText(mStoreDetails.getRollNo());
holder.bookName.setText( mStoreDetails.getBook());
holder.fine.setText("Fine:" + mStoreDetails.getFine());
holder.dept.setText(mStoreDetails.getDept());
}
#Override
public int getItemCount() {
return studentDetailsList.size();
}
class StudentViewHolder extends RecyclerView.ViewHolder {
TextView studName,rollNum,bookName,dept,fine;
public StudentViewHolder(View itemView) {
super(itemView);
studName=itemView.findViewById(R.id.studentName_prof);
rollNum = itemView.findViewById(R.id.rollNumber_prof);
bookName = itemView.findViewById(R.id.bookName_prof);
fine = itemView.findViewById(R.id.fineAmt_prof);
dept = itemView.findViewById(R.id.department_prof);
}
}
}
and here is my StoreStudentDetails class:
public class storeStudentDetails implements Serializable {
private String studentName;
private String rollNo;
private String book;
private Double fine;
private String dept;
#Exclude private String id;
public storeStudentDetails() {
}
public storeStudentDetails(String studentName, String rollNo,String book, double fine ,String dept) {
this.studentName = studentName;
this.rollNo = rollNo;
this.book = book;
this.fine = fine;
this.dept = dept;
}
public void setId(String id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public String getRollNo() {
return rollNo;
}
public String getBook() {
return book;
}
public Double getFine() {
return fine;
}
public String getDept() {
return dept;
}
public String getId() {
return id;
}
}
To solve this, please move the following lines of code:
mStoreDetailsAdapter = new storeDetailsAdapter(this,studentDetailsList);
mRecyclerView.setAdapter(mStoreDetailsAdapter);
Right before the following line of code:
mStoreDetailsAdapter.notifyDataSetChanged();
And this is because onSuccess() method has an asynchronous behavior and by the time you are setting the adapter outside the callback your list is empty.
As you can see, the easiest solution for this problem is to move those lines of code inside the callback. but if you want to use the value of your studentDetailsList outside the onSuccess() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

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