Does if else statement get executed in adapter class?
I'm trying to make a notification message like Shopee apps. So I want user to receive notification if the admin have submitted the customer tracking number, the customer will received message in the notification page that will displayed the text including their tracking number. If they don't have the tracking number yet. The notification will not supposed to be displayed on the customer page.
the yellow highlighted is the correct output but the red line is not. That notification was not supposed to come out yet because the admin has not been updated the customer order tracking number.
my apps
this is my database
adapter class
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
if (orderList.get(i).getTrackingNum() == ""){
myViewHolder.note.setText("Your order has not been shipped yet!" +orderList.get(i).dateTime);
}
else
myViewHolder.note.setText(" Your order ID :" + orderList.get(i).getDateTime()+" has been posted. The Tracking number is :" + orderList.get(i).getTrackingNum());
}
notificationClass
protected void onStart() {
super.onStart();
if (dbNotification != null) {
dbNotification.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapShot : dataSnapshot.getChildren()) {
for (DataSnapshot ds : orderSnapShot.getChildren()) {
orderList.add(ds.getValue(Order.class));
}
}
}
notificationAdapter NotificationAdapter = new notificationAdapter(orderList);
recyclerView.setAdapter(NotificationAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CustNotification.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
public class Order {
public String cust_id;
public String cart_id;
public String total;
public String name;
public String address;
public String phone;
public String status;
public String dateTime;
public String courier;
public String trackingNum;
public String methodPay;
public Order() {
}
public Order(String cust_id, String cart_id, String total, String name, String address, String phone, String status, String dateTime,String courier, String trackingNum, String methodPay) {
this.cust_id = cust_id;
this.total = total;
this.name = name;
this.address = address;
this.phone = phone;
this.cart_id = cart_id;
this.status = status;
this.dateTime=dateTime;
this.courier=courier;
this.trackingNum=trackingNum;
this.methodPay=methodPay;
}
To answer your question explicitly -- Yes, you can use logic such as if-else inside your onBindViewHolder() method.
As for why your logic may not be working, maybe you should change your if statement to use TextUtils.isEmpty and see if that works.
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
if (TextUtils.isEmpty(orderList.get(i).getTrackingNum())) {
myViewHolder.note.setText("Your order has not been shipped yet!" + orderList.get(i).dateTime);
} else {
myViewHolder.note.setText(" Your order ID :" + orderList.get(i).getDateTime() + " has been posted. The Tracking number is :" + orderList.get(i).getTrackingNum());
}
}
Related
here is model class :
I want that I get all food items from all categories one by one and
than show every single food item data in recycler view
and after getting list of all items I want that I add only those items in a list which pin value is TRUE
public class Items {
String name, desc,image, category;
int price;
boolean pin;
public Items(String name, String desc, String image, String category, int price, boolean pin) {
this.name = name;
this.desc = desc;
this.image = image;
this.category = category;
this.price = price;
this.pin = pin;
}
public Items() {
}
public boolean isPin() {
return pin;
}
public void setPin(boolean pin) {
this.pin = pin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
here is the java class file code :
when I check snapshot using snapshot.getValue() in log it gives me all categories also items, but it is not adding in a list...why ???
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("admin");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.getClass();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Items items = dataSnapshot.getValue(Items.class);
list.add(items);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
this is my database :
Your for (DataSnapshot dataSnapshot : snapshot.getChildren()){ loop only loops over one level in the database, so your dataSnapshot points to BBQ and then Chines, not to the individual food items.
Since you want to loop over two nested node levels, you need two nested loops in your code:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("admin");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.getClass();
for (DataSnapshot categorySnapshot : snapshot.getChildren()){ // 👈
for (DataSnapshot itemSnapshot : categorySnapshot.getChildren()){ // 👈
Items items = itemSnapshot.getValue(Items.class); // 👈
list.add(items);
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // 👈 Never ignore errors
}
});
I'm attempting to replicate a search function in a messaging app with Firebase and display the results in a RecyclerView.
I would like to return users whose firstname, username, or lastname start with the search input text in the same recyclerview, in that order.
I am able to successfully search by one of the children, in this case I'm searching for a user's first name, but I'm really stuck as to how to add the results from the username and lastname, and in such a way that there is no duplication (e.g. if I search "A", a user with firstname "Anna" and lastname "Albury" doesn't appear twice.
Any and all help appreciated, thanks.
Activity searchUsers method:
private void searchUsers(String s){
searchInput = search_users.getText().toString();
FirebaseRecyclerOptions<Friends> retrievedFriends = new FirebaseRecyclerOptions.Builder<Friends>()
.setQuery(FriendsRef.orderByChild("refFirstName")
.startAt(searchInput).endAt(searchInput+"\uf8ff"), Friends.class)
.build();
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> adapter =
new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(retrievedFriends) {
#Override
protected void onBindViewHolder(#NonNull #NotNull FriendsViewHolder holder, int position, #NonNull #NotNull Friends model) {
final String usersIDs = getRef(position).getKey();
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("Details").hasChild("profileImage")) {
String userImage = dataSnapshot.child("Details").child("profileImage").child("imageUrl").getValue().toString();
String profileFirstName = dataSnapshot.child("Details").child("firstname").getValue().toString();
String profileLastName = dataSnapshot.child("Details").child("lastname").getValue().toString();
String profileStatus = dataSnapshot.child("Details").child("status").getValue().toString();
String profileName = profileFirstName + " " + profileLastName;
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).into(holder.profileImage);
} else {
String profileFirstName = dataSnapshot.child("Details").child("firstname").getValue().toString();
String profileLastName = dataSnapshot.child("Details").child("lastname").getValue().toString();
String profileName = profileFirstName + " " + profileLastName;
holder.userName.setText(profileName);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError databaseError) {
}
});
}
#NonNull
#NotNull
#Override
public FriendsViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_message_layout, parent, false);
return new FriendsViewHolder(view);
}
};
myFriendsList.setAdapter(adapter);
adapter.startListening();
}
Activity onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_message);
//default function
myFriendsList = (RecyclerView) findViewById(R.id.new_message_friends_list);
myFriendsList.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
FriendsRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("Friends");
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
//search function
search_users = findViewById(R.id.new_message_search_edittext);
search_users.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = search_users.length();
if (length > 0) {
searchUsers(s.toString());
} else {
cancelSearch();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Friends class:
public class Friends {
public String firstName, lastName, status, image, uid;
public Friends (){
}
public Friends(String firstName, String lastName, String status, String image, String uid) {
this.firstName = firstName;
this.lastName = lastName;
this.status = status;
this.image = image;
this.uid = uid;
}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public String getStatus() {return status;}
public void setStatus(String lastName) {this.status = status;}
public String getImage() {return image;}
public void setImage(String image) {this.image = image;}
public String getUid() {return uid;}
public void setUid(String uid) {this.uid = uid;}
}
Sample of my database:
According to your last comment:
What I'm looking for is a way to get around this by effectively search three times, once for first names, once for last names, and once for usernames, and collate the resulting users in a single RecyclerView.
In this case, you should perform three different queries and collect all the results using Tasks.whenAllSuccess() method:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query firstQuery = rootRef...
Query secondQuery = rootRef...
Query thirdQuery = rootRef...
Task firstTask = firstQuery.get();
Task secondTask = secondQuery.get();
Task thirdTask = thirdQuery.get();
Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask, thirdTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
#Override
public void onSuccess(List<Object> list) {
//Do what you need to do with your list
}
});
But remember, to avoid duplicates, add a name to the list only if it does not exist. Then simply pass the list to an adapter, and display only the results without duplicates in a RecyclerView.
Firebase Database LinkI am trying to save data to firebase using this code.
Everything works fine. I was saving the data creating new children uder users>uid. but now when i try to save the data by creating an object and passing that object in setvalue, the app crashes. Please help.
public class RegComplete extends AppCompatActivity {
private EditText Name, Surname, Address, Tel, DateOfBirth,Username;
private String _name, _surname, _address, _Tel, _DateOfBirth,_UserName, email;
public String uid = "";
FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference mdatabase;
private DatabaseReference fdatabase;
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser objuser = auth.getCurrentUser();
List<String> lstSports = new ArrayList<String>();
List<String> lstSteden = new ArrayList<String>();
String strSport1,strSport2,strSport3;
public String strCity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_complete);
fdatabase = database.getReference();
fdatabase.child("Steden").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot DS:dataSnapshot.getChildren()) {
String CityName = DS.child("CityName").getValue(String.class);
City stad = new City(CityName);
lstSteden.add(stad.CityName);
}
final Spinner CitySpin = (Spinner) findViewById(R.id.CitySpin);
ArrayAdapter<String> CityAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSteden);
CityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CitySpin.setAdapter(CityAdapter);
CitySpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strCity = CitySpin.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
fdatabase.child("SPORTS").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds :dataSnapshot.getChildren()) {
String sportName = ds.child("SportName").getValue(String.class);
Sport objsport = new Sport(sportName);
lstSports.add(objsport.SportName);
}
final Spinner Sports1 = (Spinner) findViewById(R.id.SportSpinner1);
ArrayAdapter<String> SportAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSports);
SportAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Sports1.setAdapter(SportAdapter);
Sports1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport1 = Sports1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final Spinner Sports2 = (Spinner) findViewById(R.id.SportSpinner2);
Sports2.setAdapter(SportAdapter);
Sports2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport2 = Sports2.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final Spinner Sports3 = (Spinner) findViewById(R.id.SportSpinner3);
Sports3.setAdapter(SportAdapter);
Sports3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport3 = Sports3.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Name = findViewById(R.id.NameeditText);
_name = Name.getText().toString();
Surname = findViewById(R.id.SurnameEditText);
_surname = Surname.getText().toString();
Address = findViewById(R.id.AdressEditText);
_address = Address.getText().toString();
Tel = findViewById(R.id.TelEditText);
_Tel = Tel.getText().toString();
DateOfBirth = findViewById(R.id.DOBEditText);
_DateOfBirth = DateOfBirth.getText().toString();
Username = findViewById(R.id.UserIDEditText);
_UserName = Username.getText().toString();
email = FirebaseAuth.getInstance().getCurrentUser().getEmail().toString();
}
public void btnSave_Click(View V){
User usinfo = new User(email,_UserName,_name,_surname,_address,strCity,_Tel,_DateOfBirth,strSport1,strSport2,strSport3,uid);
mdatabase = FirebaseDatabase.getInstance().getReference("USERS");
uid = objuser.getUid();
mdatabase.child(uid).setValue(usinfo);
Intent i = new Intent(RegComplete.this, LoginActivity.class);
Toast.makeText(RegComplete.this ,"Registration Complete" ,Toast.LENGTH_SHORT).show();
startActivity(i);
}
}
The code for USER.class
public class User {
public String Email;
public String UserName;
public String Name;
public String SurName;
public String StreetAdress;
public String City;
public String Tel;
public String DOB;
public String Sport1;
public String Sport2;
public String Sport3;
public String UserId;
public User(){
// Default constructor required by Firebase
}
public User(String email, String userName, String name, String surName, String streetAdress, String city, String tel, String DOB, String sport1, String sport2, String sport3, String userId) {
Email = email;
UserName = userName;
Name = name;
SurName = surName;
StreetAdress = streetAdress;
City = city;
Tel = tel;
this.DOB = DOB;
Sport1 = sport1;
Sport2 = sport2;
Sport3 = sport3;
UserId = userId;
}
public String getEmail() {
return Email;
}
public String getUserName() {
return UserName;
}
public String getName() {
return Name;
}
public String getSurName() {
return SurName;
}
public String getStreetAdress() {
return StreetAdress;
}
public String getCity() {
return City;
}
public String getTel() {
return Tel;
}
public String getDOB() {
return DOB;
}
public String getSport1() {
return Sport1;
}
public String getSport2() {
return Sport2;
}
public String getSport3() {
return Sport3;
}
public String getUserId() {
return UserId;
}
}
And i am also trying to retrieve UserName for the user with which i am signed in in another activity.
using this code.
mdatabase.child("USERS").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userinf = ds.child(uid).getValue(User.class);
};
txtUserNaam.setText(userinf.UserName);
}
Where
DatabaseReference mdatabase = FirebaseDatabase.getInstance().getReference();
Please help
Firebase is getting confused between this field:
public String City;
And this getter:
public String getCity() {
return City;
}
The field defines a property City, while the getter defines a property city. As you can see the case is different between the two, which leads to the error message.
The easiest fix is to mark all your fields as private:
private String City;
This keeps Firebase from considering them while reading/writing users.
I am having a problem of displaying the newly added data. My onChildAdded is listening for any new notification. This new notification is saved into Firebase. My notification contains 2 child (Message and Date).
However, I'm able only to display one of the child (Date) when I add a new notification. I'm able to retrieve everything if I re-run the app but I want the changes to be made when I'm on the app itself. How can I show everything when I add a new notification? Is it because onChildAdded only listen for the previous child? If needed, I can post my adapter and getter/setter codes.
Example: I sent 2 new notifications and the listener only reads the Date. Screenshot below.
Not in order. It doesn't display the newly added notification "Message". I added "Hi2" and "Hi3".
NotificationFragment.java
public class NotificationFragment extends Fragment {
private void prepareNotification1() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userID = user.getUid();
// mRef.child("customers").child(userID).child("Notification").addListenerForSingleValueEvent(new ValueEventListener() {
// #Override
// public void onDataChange(DataSnapshot dataSnapshot) {
// for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
// System.out.println(postSnapshot.getValue());
// Notification menu = postSnapshot.getValue(Notification.class);
//// Notification menu = new Notification(postSnapshot.getValue(String.class));
// notificationList.add(menu);
// }
// mAdapter.notifyDataSetChanged();
// }
//
// #Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
//
// });
//
mRef.child("customers").child(userID).child("Notification").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("child", "onChildAdded:" + dataSnapshot.getKey());
Log.d("child", "onChildAdded:" + dataSnapshot.getValue());
Notification menu = dataSnapshot.getValue(Notification.class);
mAdapter.notifyDataSetChanged();
}
});
}
}
FirebaseMessaging
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private DatabaseReference mRef;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
final String uniqueID = UUID.randomUUID().toString();
mRef.child("customers").child(userID).child("Notification").child(uniqueID).child("Date").setValue(notificationTime);
mRef.child("customers").child(userID).child("Notification").child(uniqueID).child("Message").setValue(remoteMessage.getData().get("body"));
createNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
}
Notification.java
public class Notification {
private String Message;
private String Date;
public Notification(){
}
public Notification(String Message, String Date){
this.Message = Message;
this.Date = Date;
}
public String getDate() {
return Date;
}
public void setDate(String Date) {
this.Date = Date;
}
public String getMessage() {
return Message;
}
public void setMessage(String Message) {
this.Message = Message;
}
}
NotificationAdapter.java
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationHolder> {
private List<Notification> notificationList;
private Context mContext;
public NotificationAdapter(Context mContext, List<Notification> notificationList) {
this.mContext = mContext;
this.notificationList = notificationList;
}
#Override
public NotificationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_notification, parent, false);
return new NotificationHolder(inflatedView);
}
#Override
public void onBindViewHolder(final NotificationHolder holder, int position) {
Notification notification = notificationList.get(position);
holder.body.setText(notification.getMessage());
holder.time.setText(notification.getDate());
}
#Override
public int getItemCount() {
return notificationList.size();
}
public class NotificationHolder extends RecyclerView.ViewHolder {
public TextView body;
public TextView time;
public NotificationHolder(View view) {
super(view);
body = (TextView) view.findViewById(R.id.bodyMsg);
time = (TextView) view.findViewById(R.id.time);
}
}
}
I think i found the issue, onChildAdded gets fired only when a child is added to the list, so the first time you read them from remote or a new notification is added to the online list.
In this part of code you first add the notification object with only the Date field set, then you edit its Message
mRef.child("customers").child(userID).child("Notification").child(uniqueID).child("Date").setValue(notificationTime);
mRef.child("customers").child(userID).child("Notification").child(uniqueID).child("Message").setValue(remoteMessage.getData().get("body"));
That's why when onChildAdded is fired you can only see the Date field, if you override also the onChildChanged you'll see the Message
To solve your problem you should add to firebase the whole object like it's explained here
This should be the result, following the docs
Notification newNotification = new Notification(notificationTime, remoteMessage.getData().get("body"))
mRef.child("customers").child(userID).child("Notification").child(uniqueID).setValue(newNotification);
It looks like the case of your property names don't match with the JSON. Specifically: Firebase follows JavaBean conventions, which means that a getter/setter getName()/setName() define a property name (with a lowercase n).
I'd recommend changing your JSON data to match this naming convention. But even with the current JSON you can make things work with a few annotations:
public class Notification {
private String Message;
private String Date;
public Notification(){
}
public Notification(String Message, String Date){
this.Message = Message;
this.Date = Date;
}
#PropertyName("Date")
public String getDate() {
return Date;
}
#PropertyName("Date")
public void setDate(String Date) {
this.Date = Date;
}
#PropertyName("Message")
public String getMessage() {
return Message;
}
#PropertyName("Message")
public void setMessage(String Message) {
this.Message = Message;
}
}
I am building an app that has to read data from my firebase.I need to retrieve the children as objects.If my venueList is already populated I have no problem creating a child object in the Firebase when I hit the yesFAB button.It takes the current venue in the list and creates the respected object in my Firebase, but the logic of the app is that list to be empty and populated from the objects in the database.But whe I retrieve the object, I just get some of the properties set, the name, address and the dishesList remains null.
When I am debbuging I get the venue object added to the list, but the abovementioned properties remain null.The dataSnapshot contains all the data, but then then the object temp is created without the name , address properties and the dishList ArrayList.
Bellow is part of my code concerning this issue.
Bellow is my MainActivity with the code that is only related to the Firebase
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.i(TAG,"Entered onCreate() method in MainActivity");
//instantiating the database and getting reference
mDataBase = FirebaseDatabase.getInstance();
databaseReference = mDataBase.getReference()
long idCounter = 1;
venueList = new HashMap<>();
loadFromDatabase();
public void loadFromDatabase(){
databaseReference.child("Venues").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
//iterate through every children
for (DataSnapshot child : children){
Venue temp = child.getValue(Venue.class);
temp.setVenueId(idCounter);
venueList.put(idCounter,temp);
idCounter++;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("Error:", databaseError.toException());
}
});
}
FloatingActionButton yesFAB =
(FloatingActionButton) findViewById(R.id.acceptButton);
yesFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FoodDish current = refineList.get(0);
Venue currentVenue = venueList.get(current.getVenueId());
databaseReference.child("Venues").child(currentVenue.getName()).setValue(currentVenue);
}
});
Venue.java
public class Venue implements Parcelable{
private String name;
private String address;
private String phone;
private String imagePath;
private String category;
private ArrayList<FoodDish> dishesList;
private long venueId;
public Venue(){
//default constructor with no arguments required for calls to DataSnapshot.getValue()
// method in Firebase
}
public Venue(String name, String address,String phone,String imagePath, String category,ArrayList<FoodDish> dishesList) {
this.name = name;
this.address = address;
this.imagePath = imagePath;
this.category = category;
this.dishesList = dishesList;
this.phone = phone;
}
//getters
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getCategory() {
return category;
}
public List<FoodDish> getList(){
return this.dishesList;
}
public long getVenueId(){
return this.venueId;
}
public String getImagePath() {
return imagePath;
}
public String getPhone() {
return phone;
}
//setters
public void setName(String name) {
name = name;
}
public void setAddress(String address) {
address = address;
}
public void setTakeaway(String takeaway) {
category = takeaway;
}
public void setVenueId(long id){
if (id >0){
this.venueId = id;
}
}
public void addToList(FoodDish dish){
this.dishesList.add(dish);
}
//Parcel part
public Venue(Parcel in ) {
readFromParcel( in );
}
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<Venue> CREATOR
= new Parcelable.Creator<Venue>() {
public Venue createFromParcel(Parcel in) {
return new Venue(in);
}
public Venue[] newArray(int size){
return new Venue[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(address);
dest.writeString(phone);
dest.writeString(imagePath);
dest.writeString(category);
dest.writeLong(venueId);
}
private void readFromParcel(Parcel in ) {
name = in.readString();
address = in .readString();
phone = in.readString();
imagePath = in .readString();
category = in .readString();
venueId = in.readLong();
}
}
And this is a snapshot of my Firebase
This child was automatically created with the yesFAB and already populated venueList without using the loadFromDatabase() method when I was testing my database.
After that I reverse the logic and used the loadFromDatabase() in order to retrieve that child and load it to venueList , the venue is loaded to the list but without the name, address and the dishesList, which remains null.
Any ideas what I am doing wrong? Thanks in advance.