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.
Related
I have few tables on Firebase from where I normally retrieve data, but there is one table from where I cannot get data in the same way, although a snapshot of the table has all the values
Fragment from where I get data
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_doctors, container, false);
mClinicId = mAuth.getUid();
mDoctorList = new ArrayList<>();
mFloatingActionButton = v.findViewById(R.id.add_doctor_fab);
mEmptyListTextView = v.findViewById(R.id.empty_list_tv);
checkIsListEmpty();
mDoctorsRecyclerView = v.findViewById(R.id.doctors_rv);
mDoctorsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
RecyclerView.VERTICAL, false));
mAdapter = new DoctorAdapter(mDoctorList, getActivity());
mDoctorsRecyclerView.setAdapter(mAdapter);
DatabaseReference mReference = FirebaseDatabase.getInstance().getReference().child("employees");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Log.d("myLog", "onDataChange: snapshot " + snapshot);
for (DataSnapshot doctorSnapshot : snapshot.getChildren()){
Doctor doctor = doctorSnapshot.getValue(Doctor.class);
mDoctorList.add(doctor);
Log.d("myLog", "onDataChange: doctor " + doctor.getEmail());
}
mAdapter.setDoctors(mDoctorList);
mAdapter.notifyDataSetChanged();
checkIsListEmpty();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("myLog", "onCancelled: " + error.getMessage());
}
});
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mClinicId != null) {
startActivity(RegistrationActivity.newInstance(getActivity(),
true, mClinicId));
}
}
});
return v;
}
Doctor.java
private String mUID;
private String mEmail;
private String mSurname;
private String mName;
private String mPatronymic;
private Date mBirthDate;
private String mClinicId;
private String mPosition;
public Doctor() {
}
public Doctor(String UID, String email, String surname, String name, String patronymic, Date birthDate, String clinicId, String position) {
mUID = UID;
mEmail = email;
mSurname = surname;
mName = name;
mPatronymic = patronymic;
mBirthDate = birthDate;
mClinicId = clinicId;
mPosition = position;
}
public String getPosition() {
return mPosition;
}
public String getUID() {
return mUID;
}
public String getEmail() {
return mEmail;
}
public String getSurname() {
return mSurname;
}
public String getName() {
return mName;
}
public String getPatronymic() {
return mPatronymic;
}
public Date getBirthDate() {
return mBirthDate;
}
public String getClinicId() {
return mClinicId;
}
}
As you can see in the snapshot there is data, but when they are initialized, they are equal to null
Logs
2021-05-02 19:03:14.510 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: snapshot DataSnapshot { key = employees, value = {-MZhhQb9EaQkjOp8GLEm={uid=frrvDpFDCiVBPxHkoq328XT0XwV2, clinicId=7iNGGrbV4cXU1NnyVYy0rNIUE0w2, patronymic=dudhdh, surname=dhdjhdjdh, name=dudhd, position=dyduxh, birthDate={date=2, hours=0, seconds=0, month=4, timezoneOffset=-240, year=94, minutes=0, time=767822400000, day=1}, email=mail#mail.ru}, -MZhi2_TqCZvabIekppj={uid=IZsIIxdlw1f7E66xoNluzyc9IPT2, clinicId=frrvDpFDCiVBPxHkoq328XT0XwV2, patronymic=djdnx, surname=djdnxxn, name=xjxbx, position=jxjxnxx, birthDate={date=2, hours=0, seconds=0, month=4, timezoneOffset=-240, year=93, minutes=0, time=736286400000, day=0}, email=mail#mail.ru}} }
2021-05-02 19:03:14.512 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: doctor null
2021-05-02 19:03:14.512 20833-20833/com.rpkeffect.android.rpkpolyclinik D/myLog: onDataChange: doctor null
If I trying to get data from the other table, I can get it successfully
Firebase table
https://i.stack.imgur.com/qkjvB.png
The problem was that I didn't generate setters on my Doctor.java class
Doctor.java
public class Doctor {
private String mUID;
private String mEmail;
private String mSurname;
private String mName;
private String mPatronymic;
private Date mBirthDate;
private String mClinicId;
private String mPosition;
public Doctor() {
}
public Doctor(String UID, String email, String surname, String name, String patronymic, Date birthDate, String clinicId, String position) {
mUID = UID;
mEmail = email;
mSurname = surname;
mName = name;
mPatronymic = patronymic;
mBirthDate = birthDate;
mClinicId = clinicId;
mPosition = position;
}
public String getPosition() {
return mPosition;
}
public String getUID() {
return mUID;
}
public String getEmail() {
return mEmail;
}
public String getSurname() {
return mSurname;
}
public String getName() {
return mName;
}
public String getPatronymic() {
return mPatronymic;
}
public Date getBirthDate() {
return mBirthDate;
}
public String getClinicId() {
return mClinicId;
}
public void setUID(String UID) {
mUID = UID;
}
public void setEmail(String email) {
mEmail = email;
}
public void setSurname(String surname) {
mSurname = surname;
}
public void setName(String name) {
mName = name;
}
public void setPatronymic(String patronymic) {
mPatronymic = patronymic;
}
public void setBirthDate(Date birthDate) {
mBirthDate = birthDate;
}
public void setClinicId(String clinicId) {
mClinicId = clinicId;
}
public void setPosition(String position) {
mPosition = position;
}
When you try to map a node from Firebase Realtime Database into an object of your "Doctor", the name of the fields that exist in your class must match the name of your properties that exist in your database. Unfortunately, in your case, the fields don't match. See, the fields in your class start with "m", while in the database doesn't start with "m", which is not correct.
To solve this, you have two options, you either change the name of your properties in the class to match the one in the database, or you can use an annotation in front of the getters. For example, if you have a field called "mEmail" and the property in the database is called "email", your getter should look like this:
#PropertyName("email")
public String getEmail() {
return mEmail;
}
In this way, you tell the compiler to look for a property called "email" and not "mEmail".
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());
}
}
I created a Firebase database to store members just like contacts, am trying to fetch all the members properties stored in the database. Now the list of members is fetching correctly but the member details e.g the phone, email etc return null. Please help me out.
This the Firebase database structure:
This is my code to fetch the list of members:
members = new ArrayList<>();
member = new Member();
adapter = new AllMembersAdapter(members, this);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference().child("Rad5 Tech Hub");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
members.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()){
member = ds.getValue(Member.class);
Log.d("debugger", "member email: " + member.getEmail()); //returns null
members.add(member);
}
recyclerViewList.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here is my Member Class
public class Member {
private String mMonthName;
private String mLastName;
private String mGender;
private String mEmail;
private String mPhone;
private String mAddress;
private String mDate;
private String mOccupation;
public Member(){}
public Member(String mAddress, String mDate, String mEmail, String mGender,
String mLastName, String mMonthName, String mOccupation, String mPhone) {
this.mLastName = mLastName;
this.mGender = mGender;
this.mEmail = mEmail;
this.mPhone = mPhone;
this.mAddress = mAddress;
this.mDate = mDate;
this.mOccupation = mOccupation;
this.mMonthName = mMonthName;
}
public String getLastName() {
return mLastName;
}
public String getGender() {
return mGender;
}
public String getEmail() {
return mEmail;
}
public String getPhone() {
return mPhone;
}
public String getAddress() {
return mAddress;
}
public String getDate() {
return mDate;
}
public String getMonthName() {
return mMonthName;
}
public String getOccupation() {
return mOccupation;
}
public Map<String, Object> toMap(){
HashMap<String, Object> result = new HashMap<>();
result.put("address", mAddress);
result.put("birthday", mDate);
result.put("email", mEmail);
result.put("gender", mGender);
result.put("last name", mLastName);
result.put("month name", mMonthName);
result.put("occupation", mOccupation);
result.put("phone number", mPhone);
return result;
}
}
Here is my adapter class:
public class AllMembersAdapter extends RecyclerView.Adapter<AllMembersAdapter.MembersViewHolder> {
ArrayList<Member> members;
ListItemClickListener listItemClickListener;
public AllMembersAdapter(ArrayList<Member> members, ListItemClickListener listItemClickListener) {
this.members = members;
this.listItemClickListener = listItemClickListener;
}
#NonNull
#Override
public MembersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.member_item, parent, false);
return new MembersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MembersViewHolder holder, int position) {
Member member = members.get(position);
String _monthName = member.getMonthName();
holder.mMonth.setText(_monthName);
holder.mName.setText(member.getLastName());
holder.mDate.setText(member.getDate());
}
#Override
public int getItemCount() {
return members.size();
}
public interface ListItemClickListener{
void onListItemClick(int position);
}
public class MembersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mMonth;
TextView mName;
TextView mDate;
public MembersViewHolder(View itemView) {
super(itemView);
mMonth = (TextView) itemView.findViewById(R.id.txt_month);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDate = (TextView) itemView.findViewById(R.id.txt_date);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listItemClickListener.onListItemClick(getAdapterPosition());
}
}
}
As #TheTechWolf mentioned in his comment, the problem is that Member class fields are different then the names of the fields that you have in your Firebase database. Let's take an example, in your model class you have a field named mMonthName but in the database the corresponding field is named month name. When you are using a getter named getMonthName(), Firebase is looking after a field named monthName and not mMonthName as you have now. So to solve this, please use the following model class which contains all member fields that you need:
public class Member {
private String monthName, lastName, gender, email, phone, address, date, occupation;
public Member() {}
public Member(String monthName, String lastName, String gender, String email, String phone, String address, String date, String occupation) {
this.monthName = monthName;
this.lastName = lastName;
this.gender = gender;
this.email = email;
this.phone = phone;
this.address = address;
this.date = date;
this.occupation = occupation;
}
public String getMonthName() { return monthName; }
public String getLastName() { return lastName; }
public String getGender() { return gender; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
public String getAddress() { return address; }
public String getDate() { return date; }
public String getOccupation() { return occupation; }
}
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 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.