Not able to retrieve data from firebase - java

I have created a simple android to send and receive data from firebase. But every time I open a new activity for the data to be shown, it comes out blank.
I have tried all sorts of previously answered similar questions.
private void send(){
String n = name.getText().toString();
String b = bg.getText().toString();
String d = dob.getText().toString();
String l = loc.getText().toString();
String i = id.getText().toString();
String m = mob.getText().toString();
if(TextUtils.isEmpty(n) || TextUtils.isEmpty(b) || TextUtils.isEmpty(d) || TextUtils.isEmpty(l) || TextUtils.isEmpty(i)
|| TextUtils.isEmpty(m)){
Toast.makeText(this, "Details incomplete!!", Toast.LENGTH_SHORT).show();
}
else{
String id = root.push().getKey();
Person person = new Person(b,d,i,l,m,n);
root.child(id).setValue(person);
}
}
package com.example.yashkrishan.directory;
/**
* Created by yashkrishan on 4/1/19.
*/
public class Person {
private String bg;
private String dob;
private String id;
private String loc;
private String mob;
private String name;
public Person(String bg, String dob, String id, String loc, String mob, String name) {
this.bg = bg;
this.dob = dob;
this.id = id;
this.loc = loc;
this.mob = mob;
this.name = name;
}
public Person(){}
public void setName(String name) {
this.name = name;
}
public void setLoc(String loc) {
this.loc = loc;
}
public void setMob(String mob) {
this.mob = mob;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setBg(String bg) {
this.bg = bg;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public String getLoc() {
return loc;
}
public String getMob() {
return mob;
}
public String getDob() {
return dob;
}
public String getBg() {
return bg;
}
public String getId() {
return id;
}
}
DatabaseReference ref;
FirebaseDatabase database;
ListView listView;
ArrayList<Person> list;
ArrayAdapter<Person> adapter;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
person = new Person();
listView = (ListView)findViewById(R.id.listView);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Person");
list = new ArrayList<>();
adapter = new ArrayAdapter<Person>(this,R.layout.info, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
person = ds.getValue(Person.class);
list.add(person);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I want to display list of the data stored in firebase database into a list view in different activity.

Related

Cannot retrieve data from Firebase Realtime Database Android

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".

What is the error which causes the app to stop when retrieving data from Firebase?

This is an app that uses the Firebase database.
I have added all the data in firebase and now I need to retrieve it and display using listview.
I tried to fetch and show the data in my app from firebase but the app is stopping every time.
Take a look at the screenshot
This is the Country model class
Country.java
public class Country {
private String name;
private String total;
private String newCases;
private String totalDeaths;
private String newDeaths;
private String totalRecovered;
private String activeCases;
private String seriousCases;
public Country() {
}
public Country(String name, String total, String newCases, String totalDeaths, String newDeaths, String totalRecovered, String activeCases, String seriousCases) {
this.name = name;
this.total = total;
this.newCases = newCases;
this.totalDeaths = totalDeaths;
this.newDeaths = newDeaths;
this.totalRecovered = totalRecovered;
this.activeCases = activeCases;
this.seriousCases = seriousCases;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getNewCases() {
return newCases;
}
public void setNewCases(String newCases) {
this.newCases = newCases;
}
public String getTotalDeaths() {
return totalDeaths;
}
public void setTotalDeaths(String totalDeaths) {
this.totalDeaths = totalDeaths;
}
public String getNewDeaths() {
return newDeaths;
}
public void setNewDeaths(String newDeaths) {
this.newDeaths = newDeaths;
}
public String getTotalRecovered() {
return totalRecovered;
}
public void setTotalRecovered(String totalRecovered) {
this.totalRecovered = totalRecovered;
}
public String getActiveCases() {
return activeCases;
}
public void setActiveCases(String activeCases) {
this.activeCases = activeCases;
}
public String getSeriousCases() {
return seriousCases;
}
public void setSeriousCases(String seriousCases) {
this.seriousCases = seriousCases;
}
}
This is the Activity class
Country_List.java
public class Country_List extends AppCompatActivity {
ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference reff;
ArrayList<String> countries;
ArrayAdapter<String> adapter;
Country country;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country__list);
listView = (ListView) findViewById(R.id.listView);
country = new Country();
firebaseDatabase = FirebaseDatabase.getInstance();
reff = firebaseDatabase.getReference().child("country");
countries = new ArrayList<>();
adapter = new ArrayAdapter<>(Country_List.this, R.layout.country_info, R.id.country_info_list, countries);
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
country = ds.getValue(Country.class);
countries.add("Country Name:" + country.getName().toString() + "\n" + "Total Cases:" + country.getTotal().toString() + "\n" + "New Cases:" + country.getNewCases().toString() + "\n" + "Total Deaths:" + country.getTotalDeaths().toString() + "\n" + "New Deaths:" + country.getNewCases().toString() + "Total Recovered:" + country.getTotalRecovered().toString() + "Active Cases:" + country.getActiveCases().toString() + "\n" + "Serious Cases:" + country.getSeriousCases().toString());
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
StackTrace
com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertString(com.google.firebase:firebase-database##19.2.1:425)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##19.2.1:216)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database##19.2.1:178)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database##19.2.1:47)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##19.2.1:592)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##19.2.1:562)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##19.2.1:432)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##19.2.1:231)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##19.2.1:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##19.2.1:203)
at com.example.covid_19explorer.Country_List$1.onDataChange(Country_List.java:40)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
To solve this, you please change all the properties in your Country class to be of type long, except the name, which should remain a String. Please also change all the setters and getters. Your class should look like this:
public class Country {
private String name;
private long total, newCases, totalDeaths, newDeaths, totalRecovered, activeCases, seriousCases;
public Country() {}
public Country(String name, long total, long newCases, long totalDeaths, long newDeaths, long totalRecovered, long activeCases, long seriousCases) {
this.name = name;
this.total = total;
this.newCases = newCases;
this.totalDeaths = totalDeaths;
this.newDeaths = newDeaths;
this.totalRecovered = totalRecovered;
this.activeCases = activeCases;
this.seriousCases = seriousCases;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public long getNewCases() {
return newCases;
}
public void setNewCases(long newCases) {
this.newCases = newCases;
}
public long getTotalDeaths() {
return totalDeaths;
}
public void setTotalDeaths(long totalDeaths) {
this.totalDeaths = totalDeaths;
}
public long getNewDeaths() {
return newDeaths;
}
public void setNewDeaths(long newDeaths) {
this.newDeaths = newDeaths;
}
public long getTotalRecovered() {
return totalRecovered;
}
public void setTotalRecovered(long totalRecovered) {
this.totalRecovered = totalRecovered;
}
public long getActiveCases() {
return activeCases;
}
public void setActiveCases(long activeCases) {
this.activeCases = activeCases;
}
public long getSeriousCases() {
return seriousCases;
}
public void setSeriousCases(long seriousCases) {
this.seriousCases = seriousCases;
}
}
There is one more thing that you need to do, which is to change the type for the newCases property in the database this time, to be of type long, as it is a String now. That plus sign (+) is not recommended to be added in the database, you should add it programmatically.

My Firebase Database returns null for each Member properties

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; }
}

Upload data to firebase through a java class and retrieve one attribute in another activity

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.

Unable to retrieve all the properties from an object in Firebase to android app

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.

Categories