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);
}
Related
I'm new to Android and I know this might be a piece of cake but I'm struggling.
I was trying to create a dynamic expandable recycler view using firebase realtime database but the data is not displaying properly.
I'm passing a string from one activity to another and comparing the string to the database field and then displaying it's child components but I don't know where I'm failing.
I want to display the Parent and child field by comparing the name field with the value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_detail);
//string value from another activity
String value = getIntent().getExtras().getString("name");
recycler_view = (RecyclerView) findViewById(R.id.recycler_expand);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentReference = database.getReference().child("Tutors");
//comparing
parentReference.equalTo(value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ParentList> Parent = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String ParentKey = snapshot.getKey().toString();
snapshot.child("title").getValue();
DatabaseReference childReference =
FirebaseDatabase.getInstance().getReference().child(ParentKey);
childReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChildList> Child = new ArrayList<>();
for (DataSnapshot snapshot1:dataSnapshot.getChildren())
{
final String ChildValue = snapshot1.getValue().toString();
snapshot1.child("title").getValue();
Child.add(new ChildList(ChildValue));
}
Parent.add(new ParentList(ParentKey, Child));
DocExpandableRecyclerAdapter adapter = new DocExpandableRecyclerAdapter(Parent);
recycler_view.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database Structure
ChildList.java
public class ChildList implements Parcelable {
private String title;
public ChildList(String title) {
this.title = title;
}
protected ChildList(Parcel in) {
title = in.readString();
}
public static final Creator<ChildList> CREATOR = new Creator<ChildList>() {
#Override
public ChildList createFromParcel(Parcel in) {
return new ChildList(in);
}
#Override
public ChildList[] newArray(int size) {
return new ChildList[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String Title) {
this.title = Title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
}
Please anyone help me with this :(
Don't use equalTo().
Try this:
DatabaseReference parentReference = database.getReference().child("Tutors");
parentReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String NameKey = snapshot.getKey().toString();
if(value.equals(NameKey)){
//DO WHATEVER YOU WANT
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am using Firebase database + FirebaseUI to load certain data from Firebase to Android, but the data is not shown in recycler View.
However, by logging the getCount(), I can see that "2" is returned, which means there is data present, but not visible in recyclerView.
Here is my Model class:
public SlideshowModel(){
}
public SlideshowModel(String title, String desc, String image, String date) {
this.title = title;
this.desc = desc;
this.image = image;
this.date = date;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getImage() {
return image;
}
public String getDate() {
return date;
}
}
Here is my Adapter class:
public class SlideShowAdapter extends FirebaseRecyclerAdapter<SlideshowModel, SlideShowAdapter.ViewHolder> {
public SlideShowAdapter(#NonNull FirebaseRecyclerOptions<SlideshowModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, final int position, #NonNull SlideshowModel model) {
Picasso.get().load(R.drawable.notification).fit().centerCrop().placeholder(R.drawable.placeholders).into(holder.image);
holder.title.setText(model.getTitle());
holder.description.setText(model.getDesc());
holder.date.setText(model.getDate());
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase.getInstance().getReference("notifications").child(getRef(position).getKey()).removeValue();
}
});
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout_notifications,
parent, false);
return new ViewHolder(view);
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView image, notif_icon, share_image, download_image, delete;
TextView title, description, date;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.notif);
title = itemView.findViewById(R.id.title);
description = itemView.findViewById(R.id.description);
date = itemView.findViewById(R.id.date);
delete = itemView.findViewById(R.id.delete_notif);
Here is my Activity:
List<SlideshowModel> slideshowModelList;
SlideShowAdapter adapter;
ProgressDialog pd;
RecyclerView recycler_view;
AdView adView;
DatabaseReference dbProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_notif);
recycler_view = findViewById(R.id.recycler_view);
pd = new ProgressDialog(this);
recycler_view.setHasFixedSize(true);
setTitle("Show Notifications");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
slideshowModelList = new ArrayList<>();
dbProducts = FirebaseDatabase.getInstance().getReference("notifications");
// adView = findViewById(R.id.adView);
// MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
// AdRequest adRequest = new AdRequest.Builder().build();
// adView.loadAd(adRequest);
if (isNetworkConnected()) {
pd.setMessage("Loading");
pd.setCanceledOnTouchOutside(false);
pd.show();
final DatabaseReference dbProducts = FirebaseDatabase.getInstance().getReference("notifications");
Log.e("path1", dbProducts.toString());
dbProducts.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
// Toast.makeText(ShowNotifActivity.this, "Child Changed", Toast.LENGTH_SHORT).show();
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dbProducts.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() || !slideshowModelList.isEmpty()) {
for (DataSnapshot productSnapshot : dataSnapshot.getChildren()) {
SlideshowModel p = productSnapshot.getValue(SlideshowModel.class);
slideshowModelList.add(p);
}
FirebaseRecyclerOptions<SlideshowModel> options =
new FirebaseRecyclerOptions.Builder<SlideshowModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("notifications"), SlideshowModel.class)
.build();
adapter = new SlideShowAdapter(options);
recycler_view.setAdapter(adapter);
// adapter = new SlideShowAdapter(SlideshowModel)
String current_counts = String.valueOf(dataSnapshot.getChildrenCount());
Log.e("Curr_Count : ", current_counts);
Collections.reverse(slideshowModelList);
recycler_view.setAdapter(adapter);
// lovelyProgressDialog.dismiss();
pd.dismiss();
}
else {
Toast.makeText(ShowNotifActivity.this, "No Notifications Available", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Some Error Occured", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
});
} else {
pd.dismiss();
new AlertDialog.Builder(getApplicationContext())
.setTitle("No Internet Available")
.setMessage("Please connect to Internet to get the Notifications")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recycler_view.setLayoutManager(linearLayoutManager); // set LayoutManager to RecyclerView
}
Update
I initialised the Constructors in AdapterClass, but still no luck.
Everytime you set data to your adapter you need to call
notifyDataSetChanged()
To refresh the adapter's data.
Useful link
This question already has answers here:
How to update RecyclerView Adapter Data
(16 answers)
Closed 3 years ago.
I develop a chat app. I try to get data from firebase database and display it in a recyclerview, but it doesn't work. I searched it on Google and I tried a lot of options, but it displays nothing. What am I doing wrong?
These are the activities:
1.Main Activity(Where I want to display the data)
public class SearchActivity extends AppCompatActivity {
Toolbar sToolbar;
SearchView searchView;
RecyclerView recyclerView;
BottomNavigationView sBnv;
SearchAdapter searchAdapter;
LinearLayoutManager llm;
ArrayList<String> arrayList;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
sToolbar = findViewById(R.id.sToolbar);
recyclerView = findViewById(R.id.sRecyclerView);
sBnv = findViewById(R.id.sBnv);
searchAdapter = new SearchAdapter(arrayList, getApplicationContext());
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(getApplicationContext());
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SearchActivity.this, "Database error", Toast.LENGTH_SHORT)
.show();
}
});
2.Adapter class:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {
ArrayList<String> friendsSearchedList = new ArrayList<>();
Context mContext;
public SearchAdapter(ArrayList<String> friendsSearchedList, Context mContext){
this.friendsSearchedList = friendsSearchedList;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_user_item,parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final String username = friendsSearchedList.get(position);
holder.text.setText(username);
}
#Override
public int getItemCount() {
return friendsSearchedList == null ? 0:friendsSearchedList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text, text1, text2;
Button button;
RelativeLayout relativeLayout;
public ViewHolder(View itemView){
super(itemView);
text = itemView.findViewById(R.id.sText);
button = itemView.findViewById(R.id.addFriend);
text1 = itemView.findViewById(R.id.sText1);
text2 = itemView.findViewById(R.id.sText2);
relativeLayout = itemView.findViewById(R.id.relativeLayout);
}
}
}
3.User class:
public class User {
public String email, id, password;
public String username;
public User(String email, String username, String password){
this.email = email;
this.username = username;
this.password = password;
}
public User(){}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}
Initially the arraylist which your setting for the recyclerview is empty. When you are adding the data to that list you have to notify the recycler view adapter. So your code should look like this way:
searchAdapter = new SearchAdapter(arrayList, getApplicationContext());
// remove this line
/* recyclerView.setHasFixedSize(true);*/
llm = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
***searchAdapter.notifyDataSetChanged();***
}
}
If it’s a simple chat maybe a listview would be more convenient for you.
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
}
#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) {
}
});
This should easily do the trick…
Create a method in your SearchAdapter.class like below
public void addData(ArrayList<String> list){
this.mDataSet = list;
notifyDataSetChanged();
}
And once you receive data from Firebase database, update it to the adapter like below.You need to tell the recycler view that your data set has been updated.
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
searchAdapter.addData(arrayList); // Add this line
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SearchActivity.this, "Database error", Toast.LENGTH_SHORT)
.show();
}
});
This is the screenshot of my database:
This is the activity:
private ListView dishList;
private Button bAddNewDish;
private DishListAdapter dishListAdapter;
private FirebaseDatabase mFireDb;
private DatabaseReference mDbReference;
private ChildEventListener mChildListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dishes);
dishList = (ListView) findViewById(R.id.dishList);
bAddNewDish = (Button) findViewById(R.id.bAddNewDish);
mFireDb = FirebaseDatabase.getInstance();
mDbReference = mFireDb.getReference().child("dishlist");
ArrayList<DishElement> dishArray = new ArrayList<>();
dishListAdapter = new DishListAdapter(this,R.layout.dish_item_element,dishArray);
dishList.setAdapter(dishListAdapter);
mChildListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
DishElement dishElement = dataSnapshot.getValue(DishElement.class);
dishListAdapter.add(dishElement);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
DishElement dishElement = dataSnapshot.getValue(DishElement.class);
dishListAdapter.add(dishElement);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
DishElement dishElement = dataSnapshot.getValue(DishElement.class);
dishListAdapter.add(dishElement);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDbReference.addChildEventListener(mChildListener);
bAddNewDish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(),AddDish.class);
startActivity(i);
}
});
}
}
This is the adapter:
public class DishListAdapter extends ArrayAdapter<DishElement> {
public DishListAdapter(#NonNull Context context, int resource, ArrayList<DishElement> dishElements) {
super(context, resource, dishElements);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
DishElement dishElement = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from((Activity) getContext()).inflate(R.layout.dish_item_element,parent,false);
}
TextView dishName = (TextView) convertView.findViewById(R.id.dishName);
dishName.setText(dishElement.getName());
return convertView;
}
}
I get null as value with dishElement.getName() method. The database connection seems to be working fine but I am not getting this string value whenever a child node is added in my database.
You have problems in reading data because your fields are not named correctly. To solve this, please use a model class that looks like this:
public class DishElement {
private String description, image, menuId, name;
private double price;
public DishElement() {}
public DishElement(String description, String image, String menuId, String name, double price) {
this.description = description;
this.image = image;
this.menuId = menuId;
this.name = name;
this.price = price;
}
public String getDescription() {return description;}
public String getImage() {return image;}
public String getMenuId() {return menuId;}
public String getName() {return name;}
public double getPrice() {return price;}
}
To actually read the data correctly, remove the old data from your database and add fresh one.
To read data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dishListRef = rootRef.child("dishlist");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
DishElement dishElement = ds.getValue(DishElement.class);
dishListAdapter.add(dishElement);
Log.d("TAG", dishElement.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
dishListRef.addListenerForSingleValueEvent(eventListener);
As you can see, I have added a log statement to print out the names using:
dishElement.getName()
In this case will work for sure. In your case didn't work because Firebase was looking for a field named name and not Name (capital N).
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/......)
)};