No setter/getter Firebase - java

Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.
Can anyone tell me what I'm doing wrong because I don't have a clue?
Thank you in advance.
Photo of the database:
Code of the Activity and the Class where you can see that I have the getter and the setter.
package com.example.ipill;
public class CartActivity extends AppCompatActivity {
private TextView total;
private ImageButton removeFromCart;
private Button pay;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
public static int cart_count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
total = findViewById(R.id.TotalPrice);
removeFromCart = findViewById(R.id.removeFromCart);
mResultList = findViewById(R.id.cartList);
pay = findViewById(R.id.pay);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
// Attach a listener to read the data at our posts reference
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users_get post = dataSnapshot.getValue(Users_get.class);
System.out.println("DATAAAA: "+post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
String nome;
String surname;
Long prezzo;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void getDetails(String name,String cognome,Long price){
nome=name;
surname=cognome;
prezzo=price;
}
public void setDetails(String name, String surname, Long price) {
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
TextView user_price = (TextView)mView.findViewById(R.id.price);
user_name.setText(name);
user_surname.setText(surname);
user_price.setText(Long.toString(price));
}
}
}
CLASS
public class Users_get {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
private String name, surname;
private Long price;
}
JSON structure
{
"Cart": {
"-M0U3UXq2ZA00Jq5o9as": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0WlUbQHj1hdH40uWVF": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0WxZhI98Xb1s9Xy5HV": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
},
"-M0X00Zr64RocyQHhoFB": {
"name": "Alex",
"price": 120,
"surname": "Kyto"
}
},
"Users": {
"01": {
"Name": "Alex",
"Price": 120,
"Surname": "Kyto"
},
"02": {
"Name": "Alex",
"Price": 200,
"Surname": "Pablo"
}
}
}

In addition to other answer, To get Users_get data, according your database structure you have to go one level more.
Currently your database reference pointed to Cart. So iterate through children of cart to get cart data. Check below:
mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Users_get post = childSnapshot.getValue(Users_get.class);
System.out.println("DATAAAA: " + post);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});

Change the class to this:
public class Users_get {
private String name, surname;
private Long price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Users_get(String name,Long price,String surname) {
this.price = price;
this.name = name;
this.surname = surname;
}
public Users_get() {
}
Since you are using an IDE, then just click generate getters and setters and it will automatically do that for you instead of manually writing the methods..

You get the warning because in your Users_get class you don't have correct getters for your fields. If you have a field named name, the correct getter should be:
public String getName() {
return name;
}
And not:
public String getname() {
return name;
}
See the capital N versus lowercase n? To solve this you should change all the names of all getters in your Users_get class, as explained above.

Related

Failed to convert a value of type java.lang.String to int (in explore_fragment)

Showing error on getValue(User.class) in explore_fragment.
My explore_fragment is:
public class exploreFragment extends Fragment {
FragmentExploreBinding binding;
ArrayList<User> list = new ArrayList<>();
FirebaseAuth auth;
FirebaseDatabase database;
public exploreFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
database= FirebaseDatabase.getInstance();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding= FragmentExploreBinding.inflate(inflater, container, false);
UserAdapter adapter = new UserAdapter(getContext(),list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
binding.usersRV.setLayoutManager(layoutManager);
binding.usersRV.setAdapter(adapter);
database.getReference().child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
user.setUserID(dataSnapshot.getKey());
if(!dataSnapshot.getKey().equals(FirebaseAuth.getInstance().getUid())){
list.add(user);
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
return binding.getRoot();
}
}
User_model is:
public class User {
private String name, profession,email,password,cname;
private String profile;
private String userReff;
private int guidedCount;
private String userID;
private String coverPhoto;
public User() {
}
public int getGuidedCount() {
return guidedCount;
}
public void setGuidedCount(int guidedCount) {
this.guidedCount = guidedCount;
}
public String getCoverPhoto() {
return coverPhoto;
}
public void setCoverPhoto(String coverPhoto) {
this.coverPhoto = coverPhoto;
}
public User(String name, String profession, String email, String password, String cname) {
this.name = name;
this.profession = profession;
this.email = email;
this.password = password;
this.cname = cname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getUserReff() {
return userReff;
}
public void setUserReff(String userReff) {
this.userReff = userReff;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
User_adapter is:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder>{
Context context;
ArrayList<User> list;
public UserAdapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.user_sample,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
User user = list.get(position);
Picasso.get().load(user.getProfile()).placeholder(R.drawable.placeholder).into(holder.binding.profileImage);
holder.binding.name.setText(user.getName());
holder.binding.profession.setText(user.getProfession());
holder.binding.viewprofilebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
String visiter = list.get(holder.getAdapterPosition()).getUserID();
Intent intent= new Intent(context, VActivity.class);
intent.putExtra("usersid",visiter).toString();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
UserSampleBinding binding;
public viewHolder(#NonNull View itemView) {
super(itemView);
binding = UserSampleBinding.bind(itemView);
}
}
}
Error i am getting is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guided_app, PID: 2744
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(CustomClassMapper.java:364)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(CustomClassMapper.java:290)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:215)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(CustomClassMapper.java:179)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(CustomClassMapper.java:48)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:593)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:563)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:433)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.guided_app.fragment.exploreFragment$1.onDataChange(exploreFragment.java:60)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
The firebase database is:
"Users": {
"59fLuGGNugPcgp6b725cFnKIzKC2": {
"cname": "LIT",
"email": "Stephen#gmail.com",
"guidedCount": 0,
"name": "Stephen Wade",
"password": "123456",
"profession": "Developer # Adobe"
},
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"cname": "BIT",
"email": "anshul#gmail.com",
"guided": {
"FOQEVbKRpNYjfzAJCp1XQtnvRlh2": {
"guidedAt": 1670152487063,
"guidedBy": "FOQEVbKRpNYjfzAJCp1XQtnvRlh2"
},
"y3pV1GhdLqOnteMO64U2F4o8mMu2": {
"guidedAt": 1670151228825,
"guidedBy": "y3pV1GhdLqOnteMO64U2F4o8mMu2"
}
},
"guidedCount": 2,
"name": "Anshul Lanjewar",
"password": "123456",
"profession": "SDE # Google"
},
"FOQEVbKRpNYjfzAJCp1XQtnvRlh2": {
"cname": "SIT",
"email": "Tanvi#gmail.com",
"guidedCount": 0,
"name": "Tanvi Colson",
"password": "123456",
"profession": "Analyst # Google"
},
"Jj2RH3iopgdLU6AC3VKeeaMKAXx1": {
"cname": "PIT",
"email": "Shana#gmail.com",
"guidedCount": 0,
"name": "Shana Sharma",
"password": "123456",
"profession": "FullStack # Netflix"
},
"gAzcrP1IYmQI0ht4qfH9WGt9U7F2": {
"cname": "MIT",
"email": "John#gmail.com",
"guided": {
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"guidedAt": 1670614050015,
"guidedBy": "7kpNGqcHeBfNqf8GrVK2Hpew0L62"
}
},
"guidedCount": "gAzcrP1IYmQI0ht4qfH9WGt9U7F2",
"name": "John Adams",
"password": "123456",
"profession": "Developer # Apple"
},
"y3pV1GhdLqOnteMO64U2F4o8mMu2": {
"cname": "BIT",
"email": "kumar#gmail.com",
"guided": {
"7kpNGqcHeBfNqf8GrVK2Hpew0L62": {
"guidedAt": 1670154254299,
"guidedBy": "7kpNGqcHeBfNqf8GrVK2Hpew0L62"
}
},
"guidedCount": 1,
"name": "Kumar Mishra",
"password": "123456",
"profession": "SDE # Microsoft"
}
}
I recently started with android development, so was just stucked.
I want to create an explore_fragment in which list of users is added in recyclerView and with view_profile button we can view user profile.
As expected, the following error:
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
Arrives due to the fact that an int-type field holds a value of type String. So when deserializing, the guidedCount field is expected to hold a value of type int and not String, hence the error. The node that is responsible for the Exception is:
"guidedCount": "gAzcrP1IYmQI0ht4qfH9WGt9U7F2",
See, it holds a UID rather than a number. So to solve this, change that UID with a number.

I want to get all child of child items one by one in firebase database

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

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

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.

how to get spinner item on selection of previous spinner in android?

I have 3 spinner in my Home Activity.If i select 1 other should change according to 1st spinner.I have Country, City and Location as spinner, if i select country then city and location should change according to that.Till now i manage to get country item in spinner (item from database).Now how to get only selected item in spinner..i m confused.??
here is my Home Activity(where i am getting spinner (country) item):
public class Home extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private Spinner countrySpinner, locationSpinner, citySpinner;
private TextView cityCodeTextView;
private Button submitButton;
private ArrayList<String> country_list, location_list, city_list;
private JSONArray result;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
countrySpinner = (Spinner) findViewById(Country);
//citySpinner = (Spinner) findViewById(City);
//locationSpinner = (Spinner) findViewById(R.id.Location);
countrySpinner .setOnItemSelectedListener(this);
country_list = new ArrayList<String>();
//location_list = new ArrayList<String>();
// city_list = new ArrayList<String>();
getData();
}
private void getData(){
StringRequest
stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
Log.d("Test",response);
JSONArray result = new JSONArray(response);
//Calling method getCountry to get the Country from the JSON Array
getCountry(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountry(JSONArray jsonArrayCountry){
//Traversing through all the items in the json array
List<Country> countries = new ArrayList<>();
try {
String country_name, country_code;
JSONObject countries_object;
for (int i = 0; i < jsonArrayCountry.length(); i++) {
countries_object = jsonArrayCountry.getJSONObject(i);
country_code = countries_object.getString("id");
country_name = countries_object.getString("country");
countries.add(new Country(country_code, country_name));
}
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
countrySpinner.setPrompt("--Select Country--");
countrySpinner.setAdapter(countryAdapter);
countrySpinner.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} catch (JSONException e) {
Log.e("Home", e.getLocalizedMessage(), e);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
//textViewName.setText(getName(position));
//textViewCourse.setText(getCourse(position));
//textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
// textViewName.setText("");
// textViewCourse.setText("");
//textViewSession.setText("");
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
this is Country.java
public class Country {
private String name;
private String id;
public Country(String id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
#Override
public String toString() {
return name;
}
}
this is City.java
public class City {
private String name;
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
this is Location.java
public class Location {
private String name;
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
this is Config.java
public class Config {
//JSON URL
public static final String DATA_URL = "http://demo5...../get_country.php";
public static final String DATA_URL1 = "http://demo5...../get_jsoncity.php?id=";
//Tags used in the JSON String
public static final String DATA_URL2 = "http://demo5...../get_jsonlocation.php?id=";
//Tags used in the JSON String
//JSON array name
public static final String JSON_ARRAY = "result";
}
this is my json for 1st spinner:
[
{
"id": "1",
"country": "UAE"
},
{
"id": "2",
"country": "UK"
},
{
"id": "3",
"country": "SAUDI ARABIA"
},
{
"id": "4",
"country": "OMAN"
},
{
"id": "5",
"country": "BAHRAIN"
},
{
"id": "6",
"country": "INDIA"
}
]
this is for city if i selected id=1
[
{
"id": "1",
"city_name": "Abu Dhabi"
},
{
"id": "2",
"city_name": "Dubai"
},
{
"id": "3",
"city_name": "Sharjah"
},
{
"id": "4",
"city_name": "Ajman"
},
{
"id": "5",
"city_name": "Ummal Qwain"
}
]
I am already getting 1st spinner item i.e Country , i need to get item for city(2nd spinner) and location(3rd spinner) as per selection of 1st spinner.
Your country.class should have getter setter of city and location.
public class Country {
private String name;
private String id;
private Location loc;
ArrayList<City> Cityarr = new ArrayList<City>();
public ArrayList<City> getCityarr() {
return Cityarr;
}
public void setCityarr(ArrayList<City> Citya) {
this.Cityarr = Citya;
}
public Country(String id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public Location getLocation() {
return loc;
}
#Override
public String toString() {
return name;
}
}
and spinner.OnItemSelectedLisenter should nested
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
vbopr.get(i).getCityarr().size();
cityname.clear();
cityname.add("All");
for (int j = 0; j < vbopr.get(i).getCityarr().size(); j++) {
cityname.add(vbopr.get(i).getCityarr().get(j).getCityname());
}
try {
adpcity.notifyDataSetChanged();
} catch (NullPointerException ne) {
}
adpcity = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_items, cityname);
city.setAdapter(adpcity);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
my url contains data in xml form
example
<world>
<country>
<countryid>2</countryid>
<countryname>India</countryname>
<city>
<city_id>1462</city_id>
<city_name>abc</city_name>
</city>
<city>
<city_id>1460</city_id>
<city_name>def</city_name>
</city>
<city>
<city_id>1461</city_id>
<city_name>jkl PLANT</city_name>
</city>
</country>
<country>
<countryid>3</countryid>
<countryname>Australia</countryname>
<city>
<city_id>1462</city_id>
<city_name>gdfg PLANT</city_name>
</city>
<city>
<city_id>1460</city_id>
<city_name>xdfPLANT</city_name>
</city>
<city>
<city_id>1461</city_id>
<city_name>dfgPLANT</city_name>
</city>
<city>
<city_id>617</city_id>
<city_name>dgvdfgg</city_name>
</city>
</country>
</world>
try this:
spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if (spinner_1.getSelectedItem().equals("UAE")) {
//cal api url here to get data
// set adapter to spinner_2 here for "UAE" selected
} else if (spinner_1.getSelectedItem().equals("UK")) {
//same..
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
);

Categories