DataSnapshot.getValue无法解析类型T.

时间:2016-09-24 04:32:55

标签: java android generics firebase firebase-realtime-database

这是我的spinner类,扩展了public class HomeController : Controller { public ActionResult Index() { var lib = new MyLib.MyClass(); var msg = lib.GetUserAgent(System.Web.HttpContext.Current); lib.WriteToResponse(System.Web.HttpContext.Current, "user agent is: " + msg); return new HttpStatusCodeResult(200); } }

ScoutMetric<ArrayList<String>>

这是我的ScoutMetric类:

public class ScoutSpinner extends ScoutMetric<ArrayList<String>> {
    private int mSelectedValue;

    public ScoutSpinner() {
    }

    public ScoutSpinner(String name, ArrayList<String> values, int selectedValue) {
        super(name, values);
        mSelectedValue = selectedValue;
    }

    public int getSelectedValue() {
        return mSelectedValue;
    }

    public void setSelectedValue(int selectedValue) {
        mSelectedValue = selectedValue;
    }

    public void setSelectedValue(DatabaseReference databaseReference, int selectedValue) {
        databaseReference.child("selectedValue").setValue(selectedValue);
        mSelectedValue = selectedValue;
    }
}

我正试图获得这样的价值:

public class ScoutMetric<T> {
    private String mName;
    private T mValue;
    private int mType;

    public ScoutMetric() {
    }

    public ScoutMetric(String name, T value) {
        setName(name);
        mValue = value;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public T getValue() {
        return mValue;
    }

    public void setValue(T value) {
        mValue = value;
    }

    public void setValue(DatabaseReference databaseReference, T value) {
        databaseReference.child(Constants.FIREBASE_VALUE).setValue(value);
        mValue = value;
    }

    public int getType() {
        return mType;
    }

    public void setType(Integer type) {
        mType = type;
    }

    public ScoutMetric<T> setType(int type) {
        mType = type;
        return this;
    }
}

它应该有用,因为我明确地创建了return snapshot.getValue(new GenericTypeIndicator<ScoutSpinner>() {}); 类型:ArrayList

我做错了什么?或者这是Firebase中的错误? (顺便说一下,使用v9.6.0)

PS:这是我为解决这个问题所做的那种令人作呕的恶心(不好玩):

ScoutMetric<ArrayList<String>>

这是我的例外情况:

new ScoutSpinner(
  snapshot.child("name").getValue(String.class),
  snapshot.child("value").getValue(new GenericTypeIndicator<ArrayList<String>>() {}),
  snapshot.child("selectedValue").getValue(Integer.class)
).setType(Constants.SPINNER);

1 个答案:

答案 0 :(得分:1)

我的应用中遇到了同样的问题。我在这个答案中与杰克逊解决了:

Android Firebase Exception "Could not resolve type T"

像这样:

ObjectMapper mapper = new ObjectMapper();
ScoutSpinner spinner = mapper.convertValue(dataSnapshot.getValue(), ScoutSpinner.class);