具有多个值的枚举中的java.lang.ExceptionInInitializerError

时间:2016-01-24 04:06:28

标签: java android enums

这是enum的代码(在singleton类中):

public class GlobalStore extends Application{
.....
......
.....
public synchronized static GlobalStore getInstance() {
    if(instance==null){
        instance = new GlobalStore();
    }
    return instance;
}

.....
......

public static enum Category {
    CATEGORIA_DB(1,instance.getString(R.string.cat_dep_bel),"db"),
    CATEGORIA_EL(2,instance.getString(R.string.cat_edu_lec),"el"),
    CATEGORIA_E(3,instance.getString(R.string.cat_entre),"e"),
    CATEGORIA_EM(4,instance.getString(R.string.cat_est_mod),"em"),
    CATEGORIA_GV(5,instance.getString(R.string.cat_gas_vinos),"gv"),
    CATEGORIA_DH(6,instance.getString(R.string.cat_dis_hog),"dh"),
    CATEGORIA_S(7,instance.getString(R.string.cat_salud),"s"),
    CATEGORIA_ST(8,instance.getString(R.string.cat_ser_tec),"st"),
    CATEGORIA_T(9,instance.getString(R.string.cat_turis),"t"),
    CATEGORIA_AC(10,instance.getString(R.string.cat_arte_cultura),"ac");


    private final int id;
    private final String gloss;
    private final String code;

    Category(int mId, String mGloss, String mCode) {
        this.id = mId;
        this.gloss = mGloss;
        this.code = mCode;
    }

    public int getId() {
        return id;
    }

    public String getGloss() {
        return gloss;
    }

    public String getImagen() {
        return "icon_"+code;
    }

    public String getSelectedImagen() {
        return this.getImagen() + "_red";
    }

    public String getDrawString() {
        return "mn_"+code+"1";
    }

}

以及此行中的错误:

public static Category findCategoryById(int mId) {

    for (Category categoria : Category.values()) { //HERE is error in Category.values() -- line 327
        if (categoria.getId()==mId) {
            return categoria;
        }
    }
    return null;
}

.....
}

更新

logcat中的错误:

01-24 05:42:49.310 31800-31800/? E/AndroidRuntime: FATAL EXCEPTION: main
01-24 05:42:49.310 31800-31800/? E/AndroidRuntime: Process: com.assertsoft.beneplus.alpha, PID: 31800
01-24 05:42:49.310 31800-31800/? E/AndroidRuntime: java.lang.ExceptionInInitializerError
01-24 05:42:49.310 31800-31800/? E/AndroidRuntime:     at com.assertsoft.model.GlobalStore.findCategoriaById(GlobalStore.java:327)
01-24 05:42:49.310 31800-31800/? E/AndroidRuntime:     at com.assertsoft.adapters.ListaCuponesAdapter.getView(ListaCuponesAdapter.java:196)

2 个答案:

答案 0 :(得分:0)

我相信你的代码在这里:

Category(int mId, String mGloss, String mCode) {
        this.id = mId;
        this.gloss = mGloss;
        this.code = mCode;
    }

需要初始化三个值。但是这一行:

public static Category findCategoryById(int mId)

正在初始化其中一个。在该静态上下文中,所有参数都需要初始化。

答案 1 :(得分:-1)

问题是CATEGORIA_XX(N, instance.getString(R.string.cat_mmm)," YY")

getString活动需要解释getString。

CATEGORIA_XX(N,的 ActivityInstance.getString(R.string.cat_mmm)下," YY&#34)

它运作良好!。

非常感谢所有人。