Android Firebase Database Adding items with keys to recycler view - android

I was trying to add & show messages dynamically in recycler view but I could not figure out how to send proper data type to it's adapter. In "getNewMessage(dataSnapshot) " function, I have to add all messages to list and send it to recycler view via adapter. I tried both
MessageModel model = dataSnapshot.getValue(MessageModel.class)
and creating a SampleModel that contains List<MessageModel> list, and
SampleModel model = dataSnapshot.getValue(SampleModel.class);
They didn't work. Here sample JSON file that created with sending message:
"chat" : {
"-Ksbjn0yCEB6EXhNNCM5" : {
"author" : "Ali Alacan",
"content" : "dummy content",
"date" : "Mon Aug 28 10:29:50 GMT+03:00 2017",
"id" : "H6huNPUggjtugjsERPCRSAp1"
},
"-KsbjpUtjp0oeipjjxMI" : {
"author" : "Ali Alacan",
"content" : "dummy content",
"date" : "Mon Aug 28 10:30:00 GMT+03:00 2017",
"id" : "H6huNPUggjtugjsERPCRSAp1"
}
I'm adding new messages with code below which I learnt from firebase docs.
#Exclude
public Map<String, Object> toMap(MessageModel messageModel) {
HashMap<String, Object> result = new HashMap<>();
result.put("id", messageModel.getId());
result.put("author", messageModel.getAuthor());
result.put("content", messageModel.getContent());
result.put("date", messageModel.getDate());
return result;
}
private void sendMessage() {
if (!TextUtils.isEmpty(etMessage.getText())) {
Date currentTime = Calendar.getInstance().getTime();
String key = firebaseDatabase.push().getKey();
MessageModel message = new MessageModel(UserData.getInstance().getUserId(), UserData.getInstance().getName(), "dummy content", currentTime.toString());
Map<String, Object> messageValues = toMap(message);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/chat/" + key, messageValues);
childUpdates.put("/user-chat/" + UserData.getInstance().getUserId() + "/" + key, messageValues);
firebaseDatabase.updateChildren(childUpdates);
} else {
Snackbar snackbar = Snackbar
.make(getActivity().findViewById(R.id.dashboard_container), "Enter a message please ! " + UserData.getInstance().getName(), Snackbar.LENGTH_LONG);
snackbar.show();
}
}
My MessageModel is:
public class MessageModel {
String id;
String author;
String content;
String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public MessageModel(String id, String author, String content, String date) {
this.id = id;
this.author = author;
this.content = content;
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public MessageModel() {
}
}
And firebase listener
firebaseDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getNewMessage(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// getNewMessage(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// taskDeletion(dataSnapshot);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
RecyclerView Adapter:
public class MyMessageRecyclerViewAdapter extends RecyclerView.Adapter<MyMessageRecyclerViewAdapter.ViewHolder> {
private final List<MessageModel> mValues;
private final OnListFragmentInteractionListener mListener;
public MyMessageRecyclerViewAdapter(List<MessageModel> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_chat, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getId());
holder.mContentView.setText(mValues.get(position).getContent());
holder.mAuthor.setText(mValues.get(position).getAuthor());
holder.mDate.setText(mValues.get(position).getDate());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
TextView mAuthor;
TextView mDate;
public MessageModel mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
mAuthor = (TextView) view.findViewById(R.id.author);
mDate = (TextView) view.findViewById(R.id.date);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
Sorry for reading such a long post and thank you for your time.

You don't need to use your toMap anymore, it is making you more confused on what you're doing since You already have a POJO.
Make a List in your Activity.
ArrayList<MessageModel> myListModel = new ArrayList<MessageModel>();
Do this on your firebase Listener. Make a List on your Activity
This is for Child Added.
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
MessageModel tempMessage = dataSnapshot.getValue(MessageModel.class);
myListModel.add(tempRace);
}
Now That you have a List Model. By using the onChildAdeed by Firebase.
Use this to your supply your Adapter Model and apply it.
IMPORTANT FOR FIREBASE. In everyquery for the fire base, if you need to do something AFTER the anything else is done ex: "onChildAdded" You would need to add another listener to THE SAME DatabaseReference in your case. I have no idea, you did not include your activity even your DatabaseReference so I would provide one.
DatabaseReference myReference = firebaseDatabase.getReferane("chat");
myReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MyMessageRecyclerAdapter myMessageAdapter= new MyMessageRecyclerAdapter(myListModel, listener);
//now you have to apply this to the RecyclerView.
yourWhateverNameofTheRecyclerview.SetAdapter(myMessageAdater);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Error in retrieving data from firebase into recyclerView

In the below code, At start I am retrieving user's profile info which they saved in previous activity(This is working fine)
Now, user tries to save some targets in firebase which I want to retrieve in recyclerView whenever it is saved.There is no error in saving the data.
My app crashes whenever I tries to retrieve data into recyclerView. It works fine if I retrieve a particular data into a textView.
I have tried various ways given on Stack OverFlow but nothing seems to be working
Please help me with this.
ProfileActivity.class
#Override
protected void onStart() {
super.onStart();
//retrieving profile data
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
reference = FirebaseDatabase.getInstance().getReference("User's Details").child(uid).child("profile info");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name= (String) snapshot.child("name").getValue();
String bio = (String) snapshot.child("bio").getValue();
String imageUrl = (String) snapshot.child("imageUrl").getValue();
final_name.setText(name);
final_Bio.setText(bio);
picasso.get().load(imageUrl).into(final_profileImage);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.w("TAG",error.getMessage());
Toast.makeText(Doc_ProfilePage.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//saving challenge
private void SaveChallenge(String titleText, String description) {
int year = myCalender.get(Calendar.YEAR);
int month = myCalender.get(Calendar.MONTH);
int day = myCalender.get(Calendar.DAY_OF_MONTH);
String dateText = new StringBuilder().append(day).append("/").append(month).append("/").append(year).toString();
//getting TimeFormat
int hour = myCalender.get(Calendar.HOUR);
int minute = myCalender.get(Calendar.MINUTE);
String timeText = new StringBuilder().append(hour).append(":").append(minute).toString();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference Challengereference = FirebaseDatabase.getInstance().getReference("User's Details").child(uid).child("ChallengeDetails");
if (!timeText.equals("") && !titleText.isEmpty() && !description.isEmpty()) {
id = Challengereference.push().getKey();
ChallengeDetails ChallengeDetails = new ChallengeDetails(titleText, description, dateText, timeText);
Challengereference.child(id).setValue(ChallengeDetails).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Doc_ProfilePage.this, "Successfully saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Doc_ProfilePage.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
//adding data in recyclerView
FirebaseDatabase.getInstance().getReference("User's Details").child(uid).child("ChallengeDetails").orderByKey().
addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
final ChallengeDetails challengeDetails = snapshot.getValue(ChallengeDetails.class);
challengedetail.add(challengeDetails);
GridLayoutManager layoutManager = new GridLayoutManager(Doc_ProfilePage.this,3,RecyclerView.HORIZONTAL,false);
recyclerView.setLayoutManager(layoutManager);
GridAdapter adapter = new GridAdapter(challengedetail);
recyclerView.setAdapter(adapter);
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
GridAdapter class
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
private static final String TAG = "ActivityName";
private List<ChallengeDetails> Challengedetails;
public GridAdapter( List<ChallengeDetails> detailss) {
// this.mcontext = context;
this.Challengedetails = detailss;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.challenge_grid_view,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ChallengeDetails challenge = Challengedetails.get(position);
holder.ChallengeTitleGrid.setText(challenge.getTitle());
holder.ChallengeDescriptionGrid.setText(challenge.getDescription());
holder.ChallengeGridDate.setText(challenge.getDate());
holder.ChallengeGridTime.setText(challenge.getTime());
}
#Override
public int getItemCount() {
return Challengedetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView ChallengeTitleGrid, ChallengeDescriptionGrid, ChallengeGridDate, ChallengeGridTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ChallengeTitleGrid = itemView.findViewById(R.id.ChallengeTitleGrid);
ChallengeDescriptionGrid = itemView.findViewById(R.id.ChallengeDescriptionGrid);
ChallengeGridDate = itemView.findViewById(R.id.SelectDate);
ChallengeGridTime = itemView.findViewById(R.id.SelectTime);
}
}}
ChallengeDetails Class
public class ChallengeDetails {
String title;
String description;
String date;
String time;
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
public ChallengeDetails(String title, String description, String date, String time){
this.title = title;
this.description = description;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
Image of Firebase Database
I think orderbychild send you array of datasnapshot not single document snapshot so you have to iterate through that snapshot.
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
final ChallengeDetails challengeDetails = snapshot.getValue(ChallengeDetails.class);
challengedetail.add(challengeDetails);
}
GridLayoutManager layoutManager = new GridLayoutManager(Doc_ProfilePage.this,3,RecyclerView.HORIZONTAL,false);
recyclerView.setLayoutManager(layoutManager);
GridAdapter adapter = new GridAdapter(challengedetail);
recyclerView.setAdapter(adapter);
}

Firebase database load data into Listview

I have this DB structure:
{
"customers" : {
"-L-OcgJ0kwTNSm6HoSvG" : {
"address" : "Test Alamat",
"birthday" : "1990-12-03",
"email" : "Dodi#gmail.com",
"name" : "Dodi",
"outletID" : "2673",
"phone" : "09888777111"
}
}
}
Now i want to load all data of "customers" into ListView using FirebaseUI-Android library. And here is the codes:
Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50);
FirebaseListOptions<Customers> options = new FirebaseListOptions.Builder<Customers>()
.setLayout(R.layout.row_customer)
.setQuery(query, Customers.class)
.build();
FirebaseListAdapter<Customers> adapter = new FirebaseListAdapter<Customers>(options) {
#Override
protected void populateView(View view, Customers customer, int position) {
((TextView) view.findViewById(R.id.txtCustomerName)).setText(customer.name);
((TextView) view.findViewById(R.id.txtCustomerAddress)).setText(customer.address);
((TextView) view.findViewById(R.id.txtCustomerPhone)).setText(customer.phone);
//and i've set the adapter into ListView
((ListView)layout.findViewById(R.id.lvCustomerList)).setAdapter(adapter);
And here is Customers.java:
#IgnoreExtraProperties
public class Customers {
public String name, outletID, address, phone, birthday, email;
public Customers() {
}
public Customers(String name, String outletID, String address, String phone, String birthday, String email) {
this.name = name;
this.outletID = outletID;
this.address = address;
this.phone = phone;
this.birthday = birthday;
this.email = email;
}
}
Please help me what is the problem with my source code?
i've run it and the data failed to display (only blank on my listview). There's no errors on my Android Studio logs.
I recommend to you to create custom Adapter and to use a RecyclerView (it is faster and better than a ListView )
Something like this:
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.MessageViewHolder> {
private List<Customer> customerList;
private Context context;
public CustomerAdapter(List<Customer> customerList, Context context) {
this.customerList= customerList;
this.context = context;
}
#Override
public CustomerAdapter.MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false);
return new CustomerAdapter.MessageViewHolder(v);
}
public class CustomerViewHolder extends RecyclerView.ViewHolder {
public TextView customername, customeraddress, customerphone;
public CustomerViewHolder(View view) {
super(view);
customername = view.findViewById(R.id.txtCustomerName);
customeraddress = view.findViewById(R.id.txtCustomerAddress);
customerphone = view.findViewById(R.id.txtCustomerPhone);
}
}
#Override
public int getItemCount() {
return customerList.size();
}
#Override
public void onBindViewHolder(final CustomerAdapter.MessageViewHolder holder, final int position) {
holder.customername.setText(customerList.get(position).getName;
holder.customeraddress.setText(customerList.get(position).getAddress;
holder.customerphone.setText(customerList.get(position).getPhone;
}
And you can get the data like this:
FirebaseDatabase.getInstance().getReference().child("customers").addValueEventListener(new ValueEventlistener{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Customer> custoemrList = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
Customer customer = new Customer();
customer.setName(snapshot.child("name").getValue().toString();
...
...
customerList.add(customer);
}
customerAdapter= new customerAdapter(customerList, YourActivity.this);
recyclerView.setAdapter(chatsAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
});
And in your Customer class you have to add getters and setters.
Press Alt + Insert -> Getters and Setters -> Select All -> Enter
This should be it
Change this line of code:
Query query = FirebaseDatabase.getInstance().getReference().child("customers").limitToLast(50)
with
Query query = FirebaseDatabase.getInstance().getReference()
.child("customers")
.orderByChild("name")
.limitToLast(50);

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 is getting added into list instead of getting updated in addChildEventListener's onChildChanged()

I have some data in firebase which gets changed on some specific actions and I want that change to be shown in the app.
I have a RecyclerView in which all the data from firebase is getting populated.
Here's code:
databaseReference.child("uListings").child(AccessToken.getCurrentAccessToken().getUserId()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// recyclerview gets populated here
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
Map<String,String> map = (Map<String,String>)dataSnapshot.getValue();
Map<ArrayList<String>,ArrayList<String>> map2 = (Map<ArrayList<String>,ArrayList<String>>)dataSnapshot.getValue();
String pDescription = map.get("pDescription");
String pDuration = map.get("pDuration");
String pPrice = map.get("pPrice");
String postedAt = map.get("postedAt");
String views = map.get("views");
ArrayList<String> imageUrl = map2.get("imageUrl");
if (imageUrl != null) {
UHandler pHandler = new UHandler(imageUrl.get(0), pDescription, pDuration, pPrice, postedAt, views);
list.add(pHandler);
adapter.notifyDataSetChanged();
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getBaseContext(), "imageUrlNone", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("PDPchange", "NULL");
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here's UHandlerAdapter.java:
public class UHandlerAdapter extends RecyclerView.Adapter<UHandlerAdapter.MyViewHolder> {
private Context mContext;
private List<UHandler> listingList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView pDescription, pDuration, pPrice, postedAt, listingViews, imageUrl;
public ArrayList<String> imageUrls;
public CircleImageView pImage;
public MyViewHolder(View view) {
super(view);
pImage = (CircleImageView) view.findViewById(R.id.p_image_profile);
pDescription = (TextView) view.findViewById(R.id.p_description_profile);
pDuration = (TextView) view.findViewById(R.id.p_duration_profile);
pPrice = (TextView) view.findViewById(R.id.p_price_profile);
postedAt = (TextView) view.findViewById(R.id.p_posted_when_profile);
listingViews = (TextView) view.findViewById(R.id.listing_views_profile);
imageUrl = (TextView) view.findViewById(R.id.image_urls_profile);
}
}
public UHandlerAdapter(Context mContext, List<UProfileHandler> listingList) {
this.mContext = mContext;
this.listingList = listingList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.profile_all, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
UHandler handler = listingList.get(position);
holder.pDescription.setText(handler.getPDescriptionProfile());
holder.pDuration.setText(handler.getPDurationProfile());
holder.pPrice.setText(handler.getPPriceProfile());
holder.postedAt.setText(handler.getPostedAt());
holder.listingViews.setText(handler.getListingViews());
// loading album cover using Glide library
Glide.with(mContext)
.load(handler.getPImageProfile())
.apply(new RequestOptions().placeholder(R.drawable.ic_placeholder).error(R.drawable.ic_error))
.into(holder.pImage);
}
#Override
public int getItemCount() {
return listingList.size();
}
}
The problem is that in onChildChanged() the views which gets changed add a complete other item in the list reflecting it's changed value and not just gets updated in previously added items in onChildAdded().
How can I just update it in the previously added items itself?
You can store keys in order to update it e.g:
ArrayList<String> mKeys = new ArrayList<String>();
databaseReference.child("uListings").child(AccessToken.getCurrentAccessToken().getUserId()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// recyclerview gets populated here
String key = dataSnapshot.getKey();
mKeys.add(key);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
.......
//now we get the index to update specific value
String key = dataSnapshot.getKey();
int index = mKeys.indexOf(key);
list.set(index, pHandler);
adapter.notifyDataSetChanged();
....
}

Display firebase child objects in listview

I'm new to Firebase. I'm trying to query the firebase database and display all the child objects of the results in a ListView. I've no errors but nothing is being displayed. It doesn't crash but it doesn't do anything either. Please help me out.
The contents of my database:
Here's my code for data retrieval:
imgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
key = search.getText().toString().trim();
Firebase newRef = new Firebase("https://stockmanager-142503.firebaseio.com/Items");
Query query = newRef.orderByChild("Idno").equalTo(key);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String,Item> td = (HashMap<String,Item>) dataSnapshot.getValue();
List<Item> valuesToMatch = new ArrayList<Item>(td.values());
myAdapter myadapter=new myAdapter(getActivity(),valuesToMatch);
mlistView.setAdapter(myadapter);
}
#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(FirebaseError firebaseError) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(firebaseError.getMessage())
.setTitle("Error!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
Here's my adapter class:
public class myAdapter extends BaseAdapter {
private List<Item> items;
private Context mContext;
public myAdapter(Context mContext, List<Item> items) {
this.mContext=mContext;
this.items=items;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LinearLayout linearLayout;
Item item=items.get(i);
if (view == null) {
linearLayout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.rowitem, viewGroup, false);
} else {
linearLayout = (LinearLayout)view;
}
TextView text1=(TextView)linearLayout.findViewById(R.id.text1);
TextView text2=(TextView)linearLayout.findViewById(R.id.text2);
TextView text3=(TextView)linearLayout.findViewById(R.id.text3);
TextView text4=(TextView)linearLayout.findViewById(R.id.text4);
TextView text5=(TextView)linearLayout.findViewById(R.id.text5);
text1.setText(item.getIdno());
text2.setText(item.getName());
text3.setText(item.getBrand());
text4.setText(item.getCost());
text5.setText(item.getDate());
return null;
}
}
Here is the item class:
public class Item {
private String Type;
private String Name;
private String Brand;
private String Cost;
private String Date;
private String Store;
private String Idno;
public String getName() {
return Name;
}
public String getIdno() {
return Idno;
}
public String getCost() {
return Cost;
}
public void setDate(String date) {
Date = date;
}
public String getBrand() {
return Brand;
}
public String getStore() {
return Store;
}
public String getType() {
return Type;
}
public String getDate() {
return Date;
}
}
I fixed it myself. Apparently, the query returned a list of objects and hence I replaced the Hashmap with a for loop to getchildren and add them to a List. But my listview simply wouldn't display the retreived data. Finally, I used the firebase UI List Adpater given below and that fixed it. Thanks everyone!
imgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
key = scanContent;
Query q = dbRef.orderByChild("idno").equalTo(key);
FirebaseListAdapter<Item> adapter =new FirebaseListAdapter<Item>(getActivity(),Item.class,R.layout.rowitem,q) {
#Override
protected void populateView(View v, Item item, int position) {
TextView text1=(TextView)v.findViewById(R.id.text1);
TextView text2=(TextView)v.findViewById(R.id.text2);
TextView text3=(TextView)v.findViewById(R.id.text3);
TextView text4=(TextView)v.findViewById(R.id.text4);
TextView text5=(TextView)v.findViewById(R.id.text5);
text1.setText(item.getIdno());
text2.setText(item.getName());
text3.setText(item.getBrand());
text4.setText(item.getCost());
text5.setText(item.getDate());
solditem=item;
}
};
sell.setText("Add this result to Sold Items List?");
sList.setAdapter(adapter);
}
});

Categories

Resources