In my Android application, I am using RecyclerView with CardView. The contents of the RecyclerView are fetched from Firebase Realtime Database. For that I have used FirebaseRecyclerAdapter from FirebaseUI. The entries in the database correspond to POJO of class Bus.
public class Bus {
private String source;
private String destination;
private long available;
private String date;
private long fare;
Bus() {
}
Bus(String source,String destination,long available,String date,long fare) {
this.source = source;
this.destination = destination;
this.available = available;
this.date = date;
this.fare = fare;
}
public long getAvailable() {
return available;
}
public long getFare() {
return fare;
}
public String getDate() {
return date;
}
public String getDestination() {
return destination;
}
public String getSource() {
return source;
}
public void setAvailable(long available) {
this.available = available;
}
public void setDate(String date) {
this.date = date;
}
public void setDestination(String destination) {
this.destination = destination;
}
public void setFare(long fare) {
this.fare = fare;
}
public void setSource(String source) {
this.source = source;
}
}
In an activity, I accept the source, destination and date from the user. My intention is to display only the relevant data in the RecyclerView. This is my FirebaseRecyclerAdapter code:
FirebaseRecyclerAdapter<Bus,BusViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Bus,BusViewHolder>(Bus.class,R.layout.bus_card,BusViewHolder.class,mDatabase) {
#Override
protected void populateViewHolder(BusViewHolder viewHolder,Bus model,int position) {
if(model.getSource().equals(source) && model.getDestination().equals(destination) && model.getDate().equals(date)) // This is the criteria for displaying the card
{
viewHolder.setSource(model.getSource());
viewHolder.setDestination(model.getDestination());
viewHolder.setAvailable(model.getAvailable());
viewHolder.setDate(model.getDate());
viewHolder.setFare(model.getFare());
}
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
Here is my ViewHolder:
public static class BusViewHolder extends RecyclerView.ViewHolder {
View mView;
public BusViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setSource(String source) {
TextView src = mView.findViewById(R.id.source);
src.setText("Source " + source);
}
public void setDestination(String destination) {
TextView dest = mView.findViewById(R.id.destination);
dest.setText("Destination " + destination);
}
public void setDate(String date) {
TextView dte = mView.findViewById(R.id.date);
dte.setText("Date " + date);
}
public void setAvailable(long available) {
TextView avail = mView.findViewById(R.id.available);
avail.setText("Available Seats " + Long.toString(available));
}
public void setFare(long fare) {
TextView fre = mView.findViewById(R.id.fare);
fre.setText("Fare " + Long.toString(fare));
}
}
The problem with this approach is that it displays the relevant cards, however there are empty cards for data which does not satisfy the condition. Is it possible to selectively retrieve data into the FirebaseRecyclerAdapter? Currently, the total number of cards created in the RecyclerView is equal to the total entries in the database.
I used query object to retrieve selectively from the Realtime Database. As query doesn't support multiple orderby clauses, I had to add an additional field in my node. This is the updated firebaserecycleradapter
query = mDatabase.orderByChild("sourcedestinationdate").equalTo(source+destination+date);
FirebaseRecyclerAdapter<Bus,BusViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Bus,BusViewHolder>(Bus.class,R.layout.bus_card,BusViewHolder.class,query) {
#Override
protected void populateViewHolder(BusViewHolder viewHolder,Bus model,int position) {
viewHolder.setSource(model.getSource());
viewHolder.setDestination(model.getDestination());
viewHolder.setAvailable(model.getAvailable());
viewHolder.setDate(model.getDate());
viewHolder.setFare(model.getFare());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
Note that the last parameter in FirebaseRecyclerAdapter is query.
Related
So below are the database of my cloud firestore. That DatePosted shows 2nd December, 2019 at 8.19 pm UTC +8. According to the code I used and I run my app, it shows an unreadable number. Is it correct on how I retrieve the data from cloud firebase? If its wrong, how do I retrieve that timestamp and make it readable?
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.tvTitle);
textViewDescription = itemView.findViewById(R.id.tvDescription);
timeStamp = itemView.findViewById(R.id.tvTimestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
Forum.java
public class Forum {
private String Title;
private String Description;
private String User;
private com.google.firebase.Timestamp DatePosted;
public Forum() {
}
public Forum(String title, String description, Timestamp datePosted,String user) {
Title = title;
Description = description;
DatePosted = datePosted;
User = user;
}
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Timestamp getDatePosted() {
return DatePosted;
}
public void setDatePosted(Timestamp datePosted) {
DatePosted = datePosted;
}
}
When you query a document with a timestamp field, you will get a Timestamp object back. If you'd rather have a Date object, you can use its toDate method.
You will need to write some code to format this for display. This is a very common task for mobile and web apps.
I have the same code for another database and it works just fine, I have no Idea why it's not working here,
the onCreateViewHolder does not even get called.
(Appearently Stacks Overflow wants me to add more details to compensate for too much code so here's some unuseful Text , Text, Text , TEXT).
public class Course extends AppCompatActivity {
private RecyclerView mLocationView;
private DatabaseReference mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
mLocation = FirebaseDatabase.getInstance().getReference("FINISHEDCOURSES");
mLocation.keepSynced(true);
mLocationView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLocationView.setHasFixedSize(true);
mLocationView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Courses> options = new FirebaseRecyclerOptions.Builder<Courses>().setQuery(mLocation, Courses.class).build();
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>
(options) {
#Override
protected void onBindViewHolder(#NonNull CourseViewHolder holder, int position, #NonNull Courses model) {
holder.setText(model.getDate(), model.getDistance(), model.getDriver(), model.getPrice());
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.courses_rows, parent, false);
return new CourseViewHolder(view);
}
};
mLocationView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class CourseViewHolder extends RecyclerView.ViewHolder{
View mView;
public CourseViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setText(String Date, String start, String end, String price){
TextView dateText = mView.findViewById(R.id.dateText);
TextView startText = mView.findViewById(R.id.depart_text);
TextView endText = mView.findViewById(R.id.end_text);
TextView priceText = mView.findViewById(R.id.price);
dateText.setText(Date);
startText.setText(start);
endText.setText(end);
priceText.setText(price);
}
}
The Courses Class
public class Courses {
private String driver, date, distance, preWaitTime, price, waitTime, client;
public Courses() {
}
public Courses(String driver, String date, String distance, String preWaitTime, String price, String waitTime, String client) {
this.driver = driver;
this.date = date;
this.distance = distance;
this.preWaitTime = preWaitTime;
this.price = price;
this.waitTime = waitTime;
this.client = client;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getPreWaitTime() {
return preWaitTime;
}
public void setPreWaitTime(String preWaitTime) {
this.preWaitTime = preWaitTime;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getWaitTime() {
return waitTime;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
}
Here's The Database Structure :
Sorry I should have commented but i do not have enough reputation to do so.
I cannot see anything similar to this in your code.
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>(
Courses.class,
R.layout.Courses,// should be your layout name
CourseViewHolder.class,
mLocation
) {
#Override
protected void populateViewHolder(CourseViewHolder viewHolder, category model, final int position) {
viewHolder.setName(model.getName());
viewHolder.setImage(getApplicationContext(),model.getImage());
I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");
I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};
I'm working on a project with android and firebase real-time database.
I'm not really sure how to achieve this structure for my project.
I have a list of Users (with name, email etc).
I want to add one/or multiple item(s) for a single user.
So User1 can have:
Item1(color: Black, percentage: 90 etc etc)
Item2(...)
I am not sure if this is the correct way to structure the data or if there is a better way.
Firebase structure
And I should be able to get all items for this user and show them in a listview.
Any help how to achieve this.
I would advice you to work with RecyclerView.
The following example is used as a chat:
Firstly create your ViewHolder and Data class:
public static class FirechatMsgViewHolder extends RecyclerView.ViewHolder {
TextView userTextView;
TextView emailUserTextView;
TextView msgTextView;
CircleImageView userImageView;
public FirechatMsgViewHolder(View v) {
super(v);
userTextView = (TextView) itemView.findViewById(R.id.userTextView);
emailUserTextView = (TextView) itemView.findViewById(R.id.emailUserTextView);
msgTextView = (TextView) itemView.findViewById(R.id.msgTextView);
userImageView = (CircleImageView) itemView.findViewById(R.id.userImageView);
}
}
Data Class:
public class ChatMessage {
private String text;
private String name;
private String email;
private String photoUrl;
public ChatMessage() {
}
public ChatMessage(String name, String email, String text, String photoUrl) {
this.text = text;
this.name = name;
this.photoUrl = photoUrl;
this.email = email;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
Then add these fields into the ChatActivity:
private DatabaseReference mSimpleFirechatDatabaseReference;
private FirebaseRecyclerAdapter<ChatMessage, FirechatMsgViewHolder>
mFirebaseAdapter;
Then init all fields in your onCreate + set adapter:
//Create the reference to get data from Firebase.
mSimpleFirechatDatabaseReference = FirebaseDatabase.getInstance().getReference();
//Fill the adapter with data + add all required listeners
mFirebaseAdapter = new FirebaseRecyclerAdapter<ChatMessage,
FirechatMsgViewHolder>(
ChatMessage.class,
R.layout.chat_message,
FirechatMsgViewHolder.class,
mSimpleFirechatDatabaseReference.child("messages")) {
#Override
protected void populateViewHolder(FirechatMsgViewHolder viewHolder, ChatMessage friendlyMessage, int position) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
viewHolder.userTextView.setText(friendlyMessage.getName());
viewHolder.emailUserTextView.setText(friendlyMessage.getEmail());
viewHolder.msgTextView.setText(friendlyMessage.getText());
if (friendlyMessage.getPhotoUrl() == null) {
viewHolder.userImageView
.setImageDrawable(ContextCompat
.getDrawable(ChatActivity.this,
R.drawable.profile));
} else {
Glide.with(ChatActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(viewHolder.userImageView);
}
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int chatMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (chatMessageCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
How to send data to Firebase
// The way to send data to the database. Add any required path!
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChatMessage friendlyMessage = new
ChatMessage(mUsername,
mUseremail,
"Some text",
mPhotoUrl);
mSimpleFirechatDatabaseReference.child("messages")
.push().setValue(friendlyMessage);
}
});
You should structure your database as shown in below image. With this structure, you can get all items for a particular User and easily show them in ListView.