Recyclerview not retrieving data - android

RecyclerView messageList;
List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter mAdapter;
mAdapter = new MessageAdapter(messagesList);
messageList = (RecyclerView) findViewById(R.id.messageList);
linearLayoutManager = new LinearLayoutManager(this);
messageList.setHasFixedSize(true);
messageList.setLayoutManager(linearLayoutManager);
messageList.setAdapter(mAdapter);
private void fetchMessages() {
rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
messagesList.add(message);
mAdapter.notifyDataSetChanged();
Log.d("Tag", String.valueOf(dataSnapshot.getValue(Messages.class)));
}
#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) {
}
});
}
Adapter
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
private List<Messages> messagesList;
private FirebaseAuth mAuth;
public MessageAdapter (List<Messages>messagesList)
{
this.messagesList = messagesList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view)
{
super(view);
messageText = (TextView)view.findViewById(R.id.message_text);
}
}
#Override
public int getItemCount()
{
return messagesList.size();
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_chat_custom,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
String current_user_id = mAuth.getInstance().getCurrentUser().getUid();
Messages messages = messagesList.get(position);
String from_user = messages.getFrom();
// if (from_user!=null && from_user.equals(current_user_id)){
// holder.messageText.setBackgroundResource(R.drawable.text_background1);
// holder.messageText.setTextColor(Color.red(R.color.red));
// }else {
// holder.messageText.setBackgroundResource(R.drawable.text_background2);
// holder.messageText.setTextColor(Color.red(R.color.black));
// }
holder.messageText.setText(messages.getMessage());
}
}
Messages Class
public class Messages {
private String from;
private String message;
private String type;
private boolean seen;
private long time;
public Messages(){};
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isSeen() {
return seen;
}
public void setSeen(boolean seen) {
this.seen = seen;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
When i debugged i got this output
04-28 18:17:57.537 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#461a55
04-28 18:17:57.538 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#c9d4c6a
04-28 18:17:57.545 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#3e055b
04-28 18:17:57.546 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#f6c31f8
04-28 18:17:57.548 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#61b06d1
04-28 18:17:57.549 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#c3bc536
04-28 18:17:57.550 21546-21546/com.appmaster.akash.messageplus D/Tag: com.appmaster.akash.messageplus.Messages#94d9c37
Screenshot https://ibb.co/e9ui8c
IDS
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
MessageSenderId = mAuth.getCurrentUser().getUid();
MessageRecieverId = getIntent().getStringExtra("Recievers_Id");
Before i had a listview and it was fine... the logic was correct and so was the method so all the data was fetched and displayed in the listview... then i decided to change it to recyclerview and the methods in the recyclerview adapter had been changed so im not sure if everything is correct... please help me out

RecyclerView messageList;
ArrayList<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter mAdapter;
private Messages messages;
mAdapter = new MessageAdapter(fetchMessage(),getMessages());
messageList = (RecyclerView) findViewById(R.id.messageList);
linearLayoutManager = new LinearLayoutManager(this);
messageList.setHasFixedSize(true);
messageList.setLayoutManager(linearLayoutManager);
messageList.setAdapter(mAdapter);
private ArrayList<Messages>fetchMessages() {rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
mAdapter.notifyDataSetChanged();
Log.d("Tag", String.valueOf(dataSnapshot.getValue(Messages.class)));
}
#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) {
}
});
return messgesList
}
private Messages getMessage(){
return messages;
}
Then in your adapter
public class MessageAdapter extends
RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
private List<Messages> messagesList;
private FirebaseAuth mAuth;
private Messages messages;
public MessageAdapter (List<Messages>messagesList, Messsages messages)
{
this.messagesList = messagesList;
this.messages = messages;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view)
{
super(view);
messageText = (TextView)view.findViewById(R.id.message_text);
}
}
#Override
public int getItemCount()
{
return messagesList.size();
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View V=LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_chat_custom, parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
String current_user_id = mAuth.getInstance().getCurrentUser().getUid();
messages = messagesList.get(position);
String from_user = messages.getFrom();
// if (from_user!=null && from_user.equals(current_user_id)){
//
holder.messageText.setBackgroundResource(R.drawable.text_background1);
// holder.messageText.setTextColor(Color.red(R.color.red));
// }else {
//
holder.messageText.setBackgroundResource(R.drawable.text_background2);
//
holder.messageText.setTextColor(Color.red(R.color.black));
// }
holder.messageText.setText(messages.getMessage());
}
}

Related

Sorting recycler view items according to most recent message

I'm building a chat application using firebase, i want to sort the chat list according to most recent message. The user you sent a message to last should appear at the top. Previous messages should come below, please help!
I've already tried orderbychild("time") it didn't work.
Chats Fragment
public class ChatsFragment extends Fragment {
private View PrivateChatView;
private RecyclerView chatsList;
private RecyclerView chatsLists;
private DatabaseReference ChatsRef,
UsersRef,
RootRef,
MsgRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String currentUserID;
private String theLastMessage;
public ChatsFragment() { // Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment
PrivateChatView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
mUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Friends").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
MsgRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
RootRef = FirebaseDatabase.getInstance().getReference();
chatsList = (RecyclerView)PrivateChatView.findViewById(R.id.chats_list);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
chatsList.setLayoutManager(layoutManager);
chatsLists = (RecyclerView)PrivateChatView.findViewById(R.id.chats_lists);
chatsLists.setLayoutManager(new LinearLayoutManager(getContext()));
updateToken(FirebaseInstanceId.getInstance().getToken());
return PrivateChatView;
}
private void updateToken(String token) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Tokens");
Token token1 = new Token(token);
reference.child(currentUserID).setValue(token1);
}
#Override public void onStart() {
super.onStart();
chats();
friends();
}
private void chats() {
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(MsgRef.getRef().orderByChild("date"), Friends.class).build();
FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
#Override protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull final Friends model) {
final String usersID = getRef(position).getKey();
final String[] retImage = {
"default_image"
};
final String list_user_id = getRef(position).getKey();
Query lastMessageQuery = MsgRef.child(list_user_id).limitToLast(1);
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("time").getValue().toString();
String data1 = dataSnapshot.child("date").getValue().toString();
holder.userStatus.setText(data + " " + data1);
holder.userStatus.setTypeface(null, Typeface.NORMAL);
}
#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) {}
});
UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
chatIntent.putExtra("visit_user_id", usersID);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage);
startActivity(chatIntent);
}
});
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
#NonNull #Override public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
private void friends() {
FirebaseRecyclerOptions<Friends> options = new FirebaseRecyclerOptions.Builder<Friends>().setQuery(ChatsRef, Friends.class).build();
FirebaseRecyclerAdapter<Friends, ChatsViewHolder> adapter = new FirebaseRecyclerAdapter<Friends, ChatsViewHolder>(options) {
#Override protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull final Friends model) {
final String usersID = getRef(position).getKey();
final String[] retImage = {
"default_image"
};
final String list_user_id = getRef(position).getKey();
UsersRef.child(usersID).addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivityy.class);
chatIntent.putExtra("visit_user_id", usersID);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage);
startActivity(chatIntent);
}
});
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
#NonNull #Override public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_chat_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsLists.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userStatus,
userName;
ImageView icon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userStatus = itemView.findViewById(R.id.user_status);
userName = itemView.findViewById(R.id.user_profile_name);
icon = itemView.findViewById(R.id.user_online_status);
}
}
}

Firebase data to RecyclerView shows only one item

I'm retrieving data from firebase and trying to display that in recycler view, every thing is fine but it only shows one item in the list (there are total 14 items)
comment if you do not understand the question
This is my main activity where i get datasnapshots from firebase
public class cakes_activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Data> listdata;
private DatabaseReference mref;
private NorthAdaptor north;
private final Context context = this;
public int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cakes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
EditText editText = (EditText) findViewById(R.id.editText) ;
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//FIREBASE
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mref= FirebaseDatabase.getInstance().getReference("Cakes");
mref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Data data = dataSnapshot.getValue(Data.class);
listdata = new ArrayList<>();
listdata.add(data);
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
}
#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) {
}
});
}
and the following code is my adaptor class:
public class NorthAdaptor extends RecyclerView.Adapter<NorthAdaptor.NorthHolder> {
private LayoutInflater inflater;
ArrayList<Data> northy;
public NorthAdaptor(Context context,ArrayList<Data> northy)
{
inflater=LayoutInflater.from(context);
this.northy=northy;
}
public NorthHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item,parent,false);
NorthHolder holder = new NorthHolder(view);
return holder;
}
#Override
public void onBindViewHolder(NorthHolder holder, int position) {
holder.text2.setText(northy.get(position).getName());
holder.text3.setText("₹."+northy.get(position).getRS());
}
#Override
public int getItemCount() {
return northy.size();
}
class NorthHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView text,text2,text3;
ImageView img;
private final Context context;
public NorthHolder(View itemview)
{
super(itemview);
context = itemView.getContext();
CardView card = (CardView) itemView.findViewById(R.id.card);
text3=(TextView)itemView.findViewById(R.id.Rs);
text2 = (TextView) itemView.findViewById(R.id.itemtext2);
img = (ImageView) itemView.findViewById(R.id.itemimage);
card.setOnClickListener(this);
}
#Override
public void onClick(View view){
Toast.makeText(
cakes_activity.this,
"Your message here",
Toast.LENGTH_SHORT
).show();
}
}
}
this is my java class to store the data received from firebase
public class Data {
private String ID,Name,image,RS;
public Data(){
}
public Data(String ID, String Name, String image, String RS) {
this.ID = ID;
this.Name = Name;
this.image= image;
this.RS = RS;
}
public String getId() {
return ID;
}
public String getRS() {
return RS;
}
public void setId(String id) {
this.ID = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getimage() {
return image;
}
public void setImg(String image) {
this.image = image;
}
}
listdata = new ArrayList<>();
north = new NorthAdaptor(context,listdata);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.hasFixedSize();
recyclerView.setAdapter(north);
you need to write this code in onCreate instead of onchildadded

I'm trying to get Item Count from custom Adapter for a chat application but it always returns zero how to resolve this?

I'm making a chat application with RecyclerView and List class to store messages from Firebase Database and want to scroll at the bottom of the recylcerView when Chat Activity is opened but error is.....Adapter always returns zero while calling adapter.getItemcount() method . All messages are being displayed with no problem.
Custom Adapter java file
public class ChatCustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private FirebaseUser mUser;
private String currentUser;
private List<ChatModel> msgList;
//Constructor
public ChatCustomAdapter(List<ChatModel> msgList) {
this.msgList = msgList;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
currentUser = mUser.getUid();
}
#Override
public int getItemCount() {
return msgList.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if(viewType==0){
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_single__user_item_layout,parent,false);
return new SelfViewHolder(v);
}else if(viewType==1){
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_single_other_user_item_layout,parent,false);
return new OtherViewHolder(v);
}else{
return null;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int layout = holder.getItemViewType();
ChatModel model = msgList.get(position);
String msg = model.getMsg();
if(layout==0){
SelfViewHolder sHolder = (SelfViewHolder)holder;
sHolder.setSelfMsgItems(msg);
}else if(layout==1){
OtherViewHolder oHolder = (OtherViewHolder)holder;
oHolder.setOtherMsgItems(msg);
}
}
#Override
public int getItemViewType(int position) {
super.getItemViewType(position);
int layout;
ChatModel model = msgList.get(position);
String from = model.getFrom();
if(from.equals(currentUser)){
layout=0;
}else{
layout=1;
}
return layout;
}
class SelfViewHolder extends RecyclerView.ViewHolder{
TextView msgtxt,timetxt;
SelfViewHolder(View itemView) {
super(itemView);
msgtxt = itemView.findViewById(R.id.chat_sinhle_user_item_textview);
timetxt = itemView.findViewById(R.id.chat_sinhle_user_item_timeview);
}
void setSelfMsgItems(String data){
msgtxt.setText(data);
}
}
class OtherViewHolder extends RecyclerView.ViewHolder{
TextView msgtxt,timetxt;
public OtherViewHolder(View itemView) {
super(itemView);
msgtxt = itemView.findViewById(R.id.chat_other_user_item_textview);
timetxt = itemView.findViewById(R.id.chat_other_user_item_timeview);
}
public void setOtherMsgItems(String data){
msgtxt.setText(data);
}
}
}
Chat Activity java file
protected void onStart() {
super.onStart();
//region RETREIVING MESSAGES FROM SERVER
msgQ = mDatabase.child("messages").child(current_user).child(otherusername).orderByChild("time");
msgQ.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatModel model = dataSnapshot.getValue(ChatModel.class);
mLsit.add(msgposition++, model);
mAdapter.notifyDataSetChanged();
}
#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) {
}
});
//endregion
recyclerView.scrollToPosition(mAdapter.getItemCount()-1);
}
I think getItemCount() returns zero because you call this method outside of ChildEventListener. So you retrieve itemcount when there are no elements in mLsit yet.
The fastest and a little bit dirty solution here is to put scrollToPosition in onChildAdded method. Also, I would modify code this way
protected void onStart() {
super.onStart();
//region RETREIVING MESSAGES FROM SERVER
msgQ = mDatabase.child("messages").child(current_user).child(otherusername).orderByChild("time");
msgQ.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatModel model = dataSnapshot.getValue(ChatModel.class);
mLsit.add(msgposition, model);
mAdapter.notifyItemInserted(msgposition)
recyclerView.scrollToPosition(msgposition);
msgposition++;
}
#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) {
}
});
//endregion
}

how to retrieve all data from firebase and display on listview android?

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

Data from Firebase won't show in my RecyclerView

The data is being fetched in the fetchData() method in FirebaseHelper, but isn't actually being stored in the variables petInfo and imgURL in the CardViewAdapter. This results in no cards showing in the RecyclerView fragment. When the app initializes, the dataset is 0, runs through the fetchData and the dataset is the size of items but leaves petInfo and imgURL null.
FirebaseHelper:
public class FirebaseHelper {
private DatabaseReference mDatabase;
Boolean saved = null;
ArrayList<AnimalType> animal = new ArrayList<>();
public FirebaseHelper(DatabaseReference mDatabase) {
this.mDatabase = mDatabase;
}
//Save
public Boolean save (AnimalType animalType){
if (animalType==null){
saved = false;
}
else{
try{
mDatabase.child("AnimalType").push().setValue(animalType);
saved=true;
}catch (DatabaseException e){
e.printStackTrace();
saved=false;
}
}
return saved;
}
//Read
public ArrayList<AnimalType> retrieve(){
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
Log.i(TAG, "onChildAdded");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
Log.i(TAG, "onChildChanged");
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return animal;
}
private void fetchData (DataSnapshot dataSnapshot){
animal.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
AnimalType animalType = new AnimalType();
animalType.setPetInfo(ds.getValue(AnimalType.class).getPetInfo());
animalType.setImgURL(ds.getValue(AnimalType.class).getImgURL());
animal.add(animalType);
}
}
}
Adapter:
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
Context mContext;
private List<AnimalType> mAnimalData = new ArrayList<>();
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView petInfo;
public ImageView imgURL;
public ViewHolder(View view){
super(view);
imgURL = (ImageView) view.findViewById(R.id.pet_image);
petInfo = (TextView) view.findViewById(R.id.pet_description);
}
}
//constructor
public CardViewAdapter(Context mContext, List<AnimalType> mAnimalData){
this.mAnimalData = mAnimalData;
}
//create new views
#Override
public CardViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
mContext = parent.getContext();
return viewHolder;
}
//replace contents of view
#Override
public void onBindViewHolder(ViewHolder holder, int position){
holder.petInfo.setText(mAnimalData.get(position).getPetInfo());
PicassoClient.downloadImage(mContext,mAnimalData.get(position).getImgURL(), holder.imgURL);
}
//return size of dataset
public int getItemCount(){
return mAnimalData.size();
}
}
Fragment:
public class DogFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mCardAdapter;
private RecyclerView.LayoutManager mCardLayoutManager;
DatabaseReference mDatabaseReference;
FirebaseHelper helper;
public static DogFragment newInstance(int page) {
DogFragment dogFragment = new DogFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
dogFragment.setArguments(args);
return dogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dog, container, false);
//cardview
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.card_view);
//setup firebase
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
helper= new FirebaseHelper(mDatabaseReference);
//create adapter class
//mCardAdapter = new CardViewAdapter(mAimalTypeList);
mCardAdapter = new CardViewAdapter(getActivity().getApplicationContext(), helper.retrieve());
mRecyclerView.setAdapter(mCardAdapter);
//add linear layout manager
mCardLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mCardLayoutManager);
//preparePetData();
return rootView;
}
}
Picasso:
public class PicassoClient {
public static void downloadImage(Context context, String url, ImageView img){
if(url != null && url.length()>0){
Picasso.with(context).load(url).placeholder(R.drawable.placeholder).into(img);
}
else {
Picasso.with(context).load(R.drawable.placeholder).into(img);
}
}
}
Your call to helper.retrieve() is kicking off mDatabase.addChildEventListener the results of which will come back asynchronously....in the meantime you're returning empty list from that method (default value of animal). You need to update adapter when results come back (after you've called fetchData(dataSnapshot);)

Categories

Resources