3

I am trying to get list of cities from Firebase and showing in spinner. But I am getting following error below:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type Models.FirebaseCityModel

Database structure:

enter image description here

Below is my code:

 dRef.child("Cities").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            List<FirebaseCityModel> cities = new ArrayList<>();

            for(DataSnapshot areaSnapshot:dataSnapshot.getChildren()){
                FirebaseCityModel areaName = areaSnapshot.getValue(FirebaseCityModel.class);
                cities.add(areaName);
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,R.layout.spinner_city,
                    R.id.locaions,list);

            chooseLocation.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

            TastyToast.makeText(getApplicationContext(),"Unable to fetch locations",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
        }
    });

Someone please let me know what I am doing wrong. Any help would be appreciated.

THANKS

Digvijay
  • 2,887
  • 3
  • 36
  • 86

2 Answers2

2

Most likely the problem in code is that are making an extra .child() call. So to solve this, please change the following line of code:

FirebaseCityModel areaName = areaSnapshot.child("city").getValue(FirebaseCityModel.class);

to

FirebaseCityModel areaName = areaSnapshot.getValue(FirebaseCityModel.class);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • When I am Logging output using your solution I am getting something like this ``Models.FirebaseCityModel@f03007d`` and ``Models.FirebaseCityModel@c1b7b72``. – Digvijay Aug 02 '19 at 12:35
  • Without seeing your code, I cannot be much of a help. Beside that, before implementing that, have you tried my solution above? – Alex Mamo Aug 02 '19 at 12:39
  • I have updated my code with your code please see my post. – Digvijay Aug 02 '19 at 12:42
  • Looks good. Now, provide me the entire error message and the line at which it occurs. – Alex Mamo Aug 02 '19 at 12:52
  • There is no error but showing something like this in log cat ``Models.FirebaseCityModel@c2d88fa`` and ``Models.FirebaseCityModel@a7baeab``. – Digvijay Aug 02 '19 at 12:57
  • Oh, I understand now. In that case, please override `toString()` method in your `FirebaseCityModel` class to return your `city` string, as showed also [here](https://stackoverflow.com/questions/48622480/showing-firebase-data-in-listview). This is the simplest solution. Does it work now? Th – Alex Mamo Aug 02 '19 at 13:05
0

Inside onDataChange() change ur code to -

FirebaseCityModel areaName = areaSnapshot.getValue(FirebaseCityModel.class);
Sachin Rajput
  • 4,326
  • 2
  • 18
  • 29