Datasnapshot HashMap cannot be cast to another class

吃可爱长大的小学妹 提交于 2019-12-22 09:36:22

问题


I have added the functionality to the app I am designing to get the List of all "Job_Class" objects from my Firebase database, this is working fine, I can get all the jobs.

The issue is I need to use the collection of jobs I have retrieved however I am getting the error:

java.util.HashMap cannot be cast to (packages removed).Job_Class

This error occurs at the for loop you will see in the code below. If anyone could help me in being able to actually use the jobs retrieved I would be very grateful.

public static void setUpCityChildrenListRetriever(final Context context, String cityName)
{
    database.getReference("Cities").child(cityName).addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            Map<String, Job_Class> td = (HashMap<String, Job_Class>) dataSnapshot.getValue();

            if (td != null)
            {
                ArrayList<Job_Class> values = new ArrayList<>(td.values());
                //jobsInCityObjects = values;
                List<String> keys = new ArrayList<String>(td.keySet());
                //jobsInCityKeys = (ArrayList<String>) keys;

                for (Job_Class job: values)
                {
                    Log.d("firebase", job.getJobTitle());
                }

                Log.d("firebase", values.toString());
                Log.d("firebase", keys.toString());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError)
        {
            Main_Activity.shared_preferences_manager.setLatestErrorLog(databaseError.toString());
            Toast.makeText(context, "Database Error - Please Report", Toast.LENGTH_SHORT).show();
        }
    });
}

回答1:


There is no way for Firebase to know that each object in the Map represents a Job_Class instance. So instead of casting the results in one go, you'll need to loop over the DataSnapshot and then extract each object in turn:

    public void onDataChange(DataSnapshot dataSnapshot)
    {
        Map<String, Job_Class> td = new HashMap<String, Job_Class>()
        for (DataSnapshot jobSnapshot: dataSnapshot.getChildren()) {
            Job_Class job = jobSnapshot.getValue(Job_Class.class);
            td.put(jobSnapshot.getKey(), job);
        }

        ArrayList<Job_Class> values = new ArrayList<>(td.values());
        List<String> keys = new ArrayList<String>(td.keySet());

        for (Job_Class job: values) {
            Log.d("firebase", job.getJobTitle());
        }

    }


来源:https://stackoverflow.com/questions/37792494/datasnapshot-hashmap-cannot-be-cast-to-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!