[android]java.lang.ClassCastException: java.util.HashMap 不能转换为骑

标签: Android
发布时间: 2016/10/10 20:55:08
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
DatabaseReference ridesRef = database.getReference("rides");
ridesRef.equalTo(from).orderByChild("from").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.i(TAG, "dataSnapshot.getChildrenCount(): " + dataSnapshot.getChildrenCount());
        if (dataSnapshot.getChildrenCount() > 0) {
            ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();

            Log.i(TAG, value.toString());

            for (Ride r : value) { // error occurs here
                Log.i(TAG, "r.getTime:" + r.getTime());
                Log.i(TAG, "getFrom:" + r.getFrom());
            }
        }
    }
});

Log输出为︰

09-02 18:08:25.070 23651 23651 我 / RidesFragment: dataSnapshot.getChildrenCount(): 1

09-02 18:08:25.070 23651 23651 我 / RidesFragment: [{= Hackerscher 万得城电器,用户 Id = 0,时间 = 1472831718565,定期 = false,价格 = 0,chosenUserID = 0,活跃 = true,地方 = 1,从 = 火车总站柏林,meetingPointDescription = blaues ei}]

public class Ride {
    private String from;
    private String to;
    private long time;
    private int places;
    private String meetingPointDescription;
    private boolean regularly;
    private boolean active;
    private float price;
    private int userID;
    private int chosenUserID;

    public Ride() {
        // Default constructor required for calls to DataSnapshot.getValue(Ride.class)
    }

    public Ride(String from, String to, long time, int places, String meetingPointDescription, boolean regularly,
                boolean active, float price, int userID, int chosenUserID) {
        this.from = from;
        this.to = to;
        this.time = time;
        this.places = places;
        this.meetingPointDescription = meetingPointDescription;
        this.regularly = regularly;
        this.active = active;
        this.price = price;
        this.userID = userID;
        this.chosenUserID = chosenUserID;
    }

    // automatically generated getters and setters...
}

enter image description here

解决方法 1:

第三个 time :/ 我有我自己的问题的答案

ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();

已替换为

GenericTypeIndicator<ArrayList<Ride>> t = new GenericTypeIndicator<ArrayList<Ride>>() {};
ArrayList<Ride> value = dataSnapshot.getValue(t);

和一切都按预期方式工作。

官方微信
官方QQ群
31647020