I want to set RecyclerView with Child of Current User Id by using getCurrentUser().getUid().The data structure you can see in image below,
In image above, SQyOq80egYehjqx4sgiyeNcW8P02 is current userId and I want to get all child of those id and show in RecyclerView. In above image, the child is wed5qPTCdcQVzVlRcBrMo1NX43v1 and their value is Sep 29, 2018. My question is how to get those childern values separately and show in RecyclerView. As an example, I wrote code for Date (the value of current userId), which gives fatal error. I know error in Model class which I am unable to understand.
Note: this line gives error. Log.d("sdfsdfdgfdfsdfd", blogPost.getDate());
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Friends").child(uid);
FirebaseRecyclerOptions<BlogPost> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<BlogPost>()
.setQuery(query, BlogPost.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<BlogPost, BlogPostHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull BlogPostHolder blogPostHolder, int position, #NonNull BlogPost blogPost) {
Log.d("sdfsdfdgfdfsdfd", blogPost.getDate());
blogPostHolder.setBlogPost(blogPost);
}
#Override
public BlogPostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new BlogPostHolder(view);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter!= null) {
firebaseRecyclerAdapter.stopListening();
}
}
private class BlogPostHolder extends RecyclerView.ViewHolder {
private TextView userDateTextView;
BlogPostHolder(View itemView) {
super(itemView);
userDateTextView = itemView.findViewById(R.id.user_date);
}
void setBlogPost(BlogPost blogPost) {
String date = blogPost.getDate();
userDateTextView.setText(date);
}
}
}
Model:
public class BlogPost {
public String date;
public BlogPost() {}
public BlogPost(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
change child key in firebase to be date
The wed5qPTCdcQVzVlRcBrMo1NX43v1 in your JSON seems to be dynamic, meaning that each user has a different key. The Firebase client has no way to parse that information into your BlogPost class, which only has static properties.
This means you'll have to provide your own SnapshotParser class to convert the DataSnapshot into the BlogPost object. Based on the FirebaseUI documentation that should look something like this:
FirebaseRecyclerOptions<BlogPost> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<BlogPost>()
.setQuery(query, , new SnapshotParser<Chat>() {
#NonNull
#Override
public BlogPost parseSnapshot(#NonNull DataSnapshot snapshot) {
// first let Firebase read any static properties
BlogPost post = snapshot.getValue(BlogPost.class);
// then do the parsing of the dynamic properties ourselves
for (DataSnapshot friendSnapshot: snapshot.getChildren()) {
String friendUID = friendSnapshot.getKey();
String friendDate = friendSnapshot.getValue(String.class);
post.setDate(friendDate);
}
return post;
}
}).build();
The above code is invoked by FirebaseUI for each new snapshot it gets from the database. It first calls snapshot.getValue(BlogPost.class) to convert the static parts of the JSON into a post, and then parses the friends itself. For now it sets any value it finds to the date property of the post. You may need to modify that to fit your exact use-case.
Related
Good day everyone, I am having a bit of a struggle trying to grasp the idea on how to retrieve data from my Firebase storage to display it to my RecyclerView. The way my application is being set up, each user is able to set their own user profile picture. So the way I store the picture to cater for every user is by naming the files according to their UID. See below:
Here is my Firestore
Now I am stumped as to how I am going to display it on my RecyclerView. Currently, my RecyclerView can display the user's FullName, Email and Score like shown below:
Here's are the code that I am currently working with right now:
UserModel
public class UserModel {
private String FullName;
private String Email;
private long Score;
public UserModel() {
}
public UserModel(String fullName, String email, long score) {
this.FullName = fullName;
this.Email = email;
this.Score = score;
}
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public long getScore() {
return Score;
}
public void setScore(long score) {
Score = score;
}
UserAdapter
public class UserAdapter extends FirestoreRecyclerAdapter<UserModel,
UserAdapter.UserViewHolder> {
public UserAdapter(#NonNull FirestoreRecyclerOptions<UserModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull UserAdapter.UserViewHolder holder, int position, #NonNull UserModel model) {
holder.username.setText(model.getFullName());
holder.email.setText(model.getEmail());
holder.score.setText(model.getScore()+"");
}
#NonNull
#Override
public UserAdapter.UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_leaderboard_single, parent, false);
return new UserViewHolder(view);
}
public class UserViewHolder extends RecyclerView.ViewHolder {
CircleImageView userImage;
TextView username;
TextView email;
TextView score;
public UserViewHolder(#NonNull View itemView) {
super(itemView);
userImage = itemView.findViewById(R.id.list_image);
username = itemView.findViewById(R.id.list_username);
email = itemView.findViewById(R.id.list_email);
score = itemView.findViewById(R.id.list_score);
}
}
The Main Activity
public class Leaderboard extends Fragment{
private RecyclerView leaderboard_recycler;
private FirestoreRecyclerAdapter adapter;
private StorageReference storageReference;
FirebaseFirestore fStore;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_leaderboard, container, false);
leaderboard_recycler = view.findViewById(R.id.leaderboard_list);
setUpRecyclerView();
return view;
}
#Override
public void onStop() {
super.onStop();
if(adapter != null)
adapter.stopListening();
}
#Override
public void onStart() {
super.onStart();
if(adapter != null)
adapter.startListening();
}
private void setUpRecyclerView() {
fStore = FirebaseFirestore.getInstance();
//Query
Query query = fStore.collection("users")
.orderBy("Score", Query.Direction.DESCENDING);
//RecyclerOptions
FirestoreRecyclerOptions<UserModel> options = new FirestoreRecyclerOptions.Builder<UserModel>()
.setQuery(query, UserModel.class)
.build();
adapter = new UserAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
leaderboard_recycler.setLayoutManager(linearLayoutManager);
leaderboard_recycler.setAdapter(adapter);
leaderboard_recycler.invalidate();
}
}
I would be eternally grateful if someone can point me to the right direction on how to handle this situation. Thank you.
Your user model class should contain a property called "profilePictureUrl", which is a String type variable for storing the image url.
You should make a screen (Activity or Fragment) for user to upload their pictures to the Firebase Storage, and Firebase Storage will return that file url, just save/update it to your user object.
For displaying the images, use the modern image loading library Glide.
Firebase Storage tutorial: https://youtu.be/r4HgdJKM5ko
Glide tutorial: https://youtu.be/eiP-vnSM0OM
My Chat app demo: https://youtu.be/iTXCn3NVqDM
I am trying to create a ChatApp. So, I want to find out if in my contact list anyone has registered in my app or not.
As in the above image, there are 3 keys. El7SIqgHmWTsZCl6gVaXidKGsok1 This is me and others 2 are my friends and I have their phoneNumber also. So, I wanna display these 2 as my friends in my app. But It doesn't show any users.
Here is the Code that I Have tried.
public class UsersFragment extends Fragment {
RecyclerView recyclerView;
ContactsAdapter adapter;
List<Users> contactsList, userList;
DatabaseReference reference;
String userId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
reference = FirebaseDatabase.getInstance().getReference().child("Users");
contactsList = new ArrayList<>();
userList = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
userId = user.getUid();
return view;
}
private void getContactList() {
Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
;
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Users contacts = new Users(name, phone, "", "");
contactsList.add(contacts);
if (contactsList.contains(contacts)) {
cursor.moveToNext();
}
getActualUsers(contacts);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getContactList();
}
private void getActualUsers(final Users contacts) {
Query query = reference.orderByChild("number").equalTo(contacts.getPhoneNumber());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users users = dataSnapshot.getValue(Users.class);
userList.add(users);
}
Log.d("contact", String.valueOf(userList.size()));
adapter = new ContactsAdapter(getContext(), userList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
My Model Class
public class Users {
String username, phoneNumber, userId, profilephotoURL;
public Users(){}
public Users(String username, String phoneNumber, String userId, String profilephotoURL) {
this.username = username;
this.phoneNumber = phoneNumber;
this.userId = userId;
this.profilephotoURL = profilephotoURL;
}
public String getUsername() {
return username;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getUserId() {
return userId;
}
public String getProfilephotoURL() {
return profilephotoURL;
}
}
My Adapter Class
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
Context mContext;
List<Users> mList;
public UsersAdapter(Context mContext, List<Users> mList) {
this.mContext = mContext;
this.mList = mList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.display_contacts, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final Users users = mList.get(position);
holder.name.setText(users.getUsername());
holder.number.setText(users.getPhoneNumber());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ChatActivity.class);
intent.putExtra("name", users.getUsername());
intent.putExtra("userid", users.getPhoneNumber());
intent.putExtra("id", users.getUserId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, number;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.contactName);
number = itemView.findViewById(R.id.contactNumber);
}
}
}
Any Help or Suggestions?
Not sure if this is the solution to your problem, but it might be and it is too long for a comment to explain:
Let me write your code in a commpressed way with some comments:
// start a loop over every local contacts on the phone
while (cursor.moveToNext()) {
// create a local variable for this contact (the class name should be Contact. Singular.)
Contacts contacts = new Contacts(name, phone, "");
// get a contact with the same phone number from firebase.
// the sorting is executed for every iteration of the loop -> bad performance.
// -> I recommend to order the reference outside of the loop.
Query query = reference.orderByChild("number").equalTo(contacts.getNumber());
// now you add the ValueEventListener
// if onDataChanged is called, you iterate over all children of the new snapshot
// you create again a local Contacts object
// then there is this strange comparison of name and phone...don't know what that accomplishes, but ok
// now comes the part that might cause the wrong behaviour:
userList.add(contacts1);
adapter = new ContactsAdapter(getContext(), userList);
recyclerView.setAdapter(adapter);
}
So the last 3 lines seem error-prone:
userList.add(contacts1);
adapter = new ContactsAdapter(getContext(), userList);
recyclerView.setAdapter(adapter);
In general there is not much wrong with them, but keep in mind that you are basically still in the very first loop that you started in getContactList()
That means that you create a completely new adapter for every contact in the loop and assign this new adapter to the recyclerView.
Let's say you have 100 contacts on your phone. This leads to 100 adapters being created and set to the recyclerView.
I would suggest 2 major changes in your code:
override onViewCreated and put the getContactList(); in there. The method onCreateView should only be concerned with basic view inflation and maye initializing simple View variables. Filling the View with data should be done afterwards in onViewCreated.
Make a clear separation between "preparing the data for the View" and "putting the prepared data into the View". In other words: First create your final userList and only if this list is done, create the adapter and set it to the recyclerView.
If you want to improve even further, have a look at the idea of ViewModels. In short: The ViewModel is preparing all the data that its View wants to display (including filtering, transforming, etc.). The View (in this case your Fragment) is as "stupid" as possible -> It waits until the ViewModel passes data into it and does nothing more than to display that data.
LiveData is very useful for this approach and it will make your code much much cleaner and easier to understand and to maintain :)
Good luck with your project!
I'll not give you any code but an architectural hint on how to achieve your goal. From details provided in your question, I assume your clients are registering through OTP. When they sign in you can store their UID against their phone numbers. Take a look on how to save user details.
Here is how your firebase stored registered users should look like
registeredUsers : {
"23492hsdfs08fv9x9" : "0X20-342234...",
"34928304283438d8f" : "0X02-123123..."
}
Now when you access current user contact list, loop through the usrs list in firebase to see which phone numbers from contact list are also in firebase.
You could use just list of phone numbers without adding Firebase UIDs but I recommend you do it like above in case you need to map a contact number to it's UID and then you can fetch that user's details from UID as well.
Hope I've given you a hint on how to get along.
So, I was able to identify the problem, and Now I have got a Solution. So, I am posting it in case of someone needs it.
Here is the Whole Changed code for User Fragment
public class UsersFragment extends Fragment {
RecyclerView recyclerView;
UsersAdapter adapter;
List<String> contactsList;
DatabaseReference reference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
contactsList = new ArrayList<>();
return view;
}
private void getContactList() {
Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (cursor.moveToNext()) {
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactsList.contains(phone)) {
cursor.moveToNext();
} else {
contactsList.add(phone);
}
}
getActualUser();
Log.d("contact: ", String.valueOf(contactsList.size()));
}
private void getActualUser() {
reference = FirebaseDatabase.getInstance().getReference().child("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<Users> actualuserList = new ArrayList<>();
actualuserList.clear();
if (snapshot.exists()) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Users user = dataSnapshot.getValue(Users.class);
for (String number : contactsList){
if (user.getPhoneNumber().equals(number)){
actualuserList.add(user);
}
}
}
Log.d("actual: ", String.valueOf(actualuserList.size()));
adapter = new UsersAdapter(getContext(), actualuserList);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getContactList();
}
}
I am trying to create a real time database with firebase, and my information isn't being stored how it should be. The JSON data is formatted as follows:
How do I get rid of the multiple instances of djProfile? And what does that random string of letters and numbers mean in that hierarchical tree?
Here is my android classes that Im using to try and retrieve this information and store it in my firebase recyclerview:
DjProfile class:
public class DjProfile
{
String djName, uniqueID;
public DjProfile(){}
public DjProfile(String djName, String uniqueID)
{
this.djName = djName;
this.uniqueID = uniqueID;
}
public String getDjName() { return djName; }
public String getUniqueID() {return uniqueID; }
}
RecyclerView information:
RecyclerView recyclerView = findViewById(R.id.dj_result_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("djProfile");
FirebaseRecyclerOptions<DjProfile> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<DjProfile>()
.setQuery(query, DjProfile.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DjProfile, ResultsViewHolder>(firebaseRecyclerOptions)
{
#NonNull
#Override
public ResultsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.searchitem_list, viewGroup, false);
return new ResultsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ResultsViewHolder holder, int position, #NonNull DjProfile model) {
holder.setDjProfile(model);
}
};
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 ResultsViewHolder extends RecyclerView.ViewHolder
{
private TextView djNameView;
public ResultsViewHolder(View itemView)
{
super(itemView);
djNameView = itemView.findViewById(R.id.result_dj);
}
void setDjProfile(DjProfile profile)
{
String djName = profile.getDjName();
djNameView.setText(djName);
}
}
How can I retrieve just the name inside that djProfile? What am I missing?
Any feedback is greatly appreciated!
what does that random string of letters and numbers mean in that hierarchical tree?
The key starting with -Lar is created each time you call push() on a reference. It's Firebase's equivalent of an array index. To learn more about them, see The 2^120 Ways to Ensure Unique Identifiers and Best Practices: Arrays in Firebase.
This question already has answers here:
FirebaseListAdapter not pushing individual items for chat app - Firebase-Ui 3.1
(2 answers)
Closed 4 years ago.
I'm trying to implement a FirebaseRecyclerAdapter For the first time, but it just never gets called! I've checked the Firebase Guide Here but no good.
Have also checked similar threads that reported "Deleting Has FixedSize()" fixed it for them but that's not the case Here
Here's part of my database
and Here's my code for the adapter and model:
FirebaseRecyclerAdapter<Complaint, ComplaintHolder> TestAdapter;
DatabaseReference mRef;
FirebaseUser mUser;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUser = FirebaseAuth.getInstance().getCurrentUser();
mRef = FirebaseDatabase.getInstance().getReference("AccountsComplaintBasdNode").child(mUser.getUid());
Query query = mRef;
FirebaseRecyclerOptions<Complaint> mOptions = new FirebaseRecyclerOptions.Builder<Complaint>()
.setQuery(query, Complaint.class)
.build();
if (TestAdapter == null) {
TestAdapter = new FirebaseRecyclerAdapter<Complaint, ComplaintHolder>(mOptions) {
#NonNull
#Override
public ComplaintHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.list_item, viewGroup, false);
Toast.makeText(getActivity(), "Please get called", Toast.LENGTH_SHORT).show();
return new ComplaintHolder(v);
}
#Override
protected void onBindViewHolder(#NonNull ComplaintHolder holder, int position, #NonNull Complaint model) {
holder.TitleTv.setText(model.getComplaintTitle());
SimpleDateFormat smf = new SimpleDateFormat("yyyy/MM/dd");
String dateString = smf.format(model.getDate());
holder.DateTv.setText(dateString);
}
///Model Object here
public Complaint() {
}
private String ComplaintTitle;
private String details;
private Date mDate;
private String PhotoUrl;
public Complaint(String complaintTitle, String details, Date date, String photoUrl) {
ComplaintTitle = complaintTitle;
this.details = details;
mDate = date;
PhotoUrl = photoUrl;
}
public void setComplaintTitle(String complaintTitle) {
ComplaintTitle = complaintTitle;
}
public void setDetails(String details) {
this.details = details;
}
public void setDate(Date date) {
this.mDate = date;
}
public void setPhotoUrl(String photoUrl) {
PhotoUrl = photoUrl;
}
public String getComplaintTitle() {
return ComplaintTitle;
}
public String getDetails() {
return details;
}
public Date getDate() {
return mDate;
}
public String getPhotoUrl() {
return PhotoUrl;
}
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
So seems only you need is to call TestAdapter.startListening(); in onStart() method and don't forget to call TestAdapter.stopListening(); in onStop() as well but before calling stopListening() always check agains null
like:if(TestAdapter != null)
For more information and example: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md
I am using FirebaseUI to get some values from my real-time database to Firebase RecyclerView. So.. my data looks like that:
users:
userid:
info:
Name:Muhammad
I don't know how to get the value of Name which means what exactly should I do in the Users class? Here is my code (I think that the problem is in class user, I just don't know how to access child info)
public class User {
private String name;
private String email;
private String state;
private String image;
private String thumbnail;
public User(String name, String state, String image) {
this.name = name;
this.state = state;
this.image = image;
}
public User() {
}
public String getName() {
return name;
}
public String getState() {
return state;
}
public String getImage() {
return image;
}
}
my Main Activity
myDB refer to and on start method (updated after SUPERCILEX comment )
mDb = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_COLUMN);
#Override
protected void onStart() {
super.onStart();
Query query = mDb;
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, new SnapshotParser<User>() {
#NonNull
#Override
public User parseSnapshot(#NonNull DataSnapshot snapshot) {
String Name = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.NAME_COLUMN).getValue().toString();
String State = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.STATE_COLUMN).getValue().toString();
String Image = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.IMAGE_COLUMN).getValue().toString();
User user = new User(Name,State,Image);
return user;
}
}).build();
FirebaseRecyclerAdapter<User,Users_ViewHolder> adapter = new FirebaseRecyclerAdapter<User, Users_ViewHolder>(options) {
#NonNull
#Override
public Users_ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user,parent,false);
return new Users_ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Users_ViewHolder holder, int position, #NonNull User model) {
holder.Set_Name(model.getName());
holder.Set_Image(model.getImage());
holder.Set_State(model.getState());
}
};
mUsers.setAdapter(adapter);
}
my ViewHolder
public class Users_ViewHolder extends RecyclerView.ViewHolder{
View mView;
public Users_ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void Set_Name(String Name)
{
TextView mName = mView.findViewById(R.id.tv_single_user_name);
mName.setText(Name);
}
public void Set_Image(String url)
{
CircleImageView mImage = mView.findViewById(R.id.iv_single_user);
Picasso.get().load(url).placeholder(R.drawable.profile).into(mImage);
}
public void Set_State(String State)
{
TextView mState = mView.findViewById(R.id.tv_single_user_state);
mState.setText(State);
}
}
thanks
I believe it'll come in as a Map<String, Object> on the field info. However, you can always use a custom SnapshotParser to build your model to your liking: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#using-the-firebaserecycleradapter.
Some Advices :would you mind changing the set methods names?
from Set_State to setState,I too had similar problems please respect Java naming conventions
Also add the set methods in your custom model
Second:
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
Start Listening:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
stopListening() call removes the event listener and all data in the adapter
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Here you have a very good explained example