Java long不能转换为字符串

时间:2017-06-19 17:06:47

标签: java casting

我创建了一个保存和加载BigInteger和String变量的程序。当我启动程序时,它会显示异常:

  

java.lang.ClassCastException:java.lang.Long无法强制转换为java.lang.String

它说它发生在这里:

robotPrices[0] = new BigInteger(sharedPreferences.getString("rbt1price", "100"));

我的保存方法:

public void save() {
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    editor.putString("rbt1price", robotPrices[0].toString());
    editor.putString("rbt2price", robotPrices[1].toString());
    editor.putString("rbt3price", robotPrices[2].toString());
    editor.putString("rbt4price", robotPrices[3].toString());
    editor.putString("rbt5price", robotPrices[4].toString());
    editor.putString("rbt1qu", robotQu[0].toString());
    editor.putString("rbt2qu", robotQu[1].toString());
    editor.putString("rbt3qu", robotQu[2].toString());
    editor.putString("rbt4qu", robotQu[3].toString());
    editor.putString("rbt5qu", robotQu[4].toString());

    editor.putLong("lvl", lvl);
    editor.apply();
}

我的加载方法:

private void load() {


SharedPreferences sharedPreferences = 
PreferenceManager.getDefaultSharedPreferences(this);

    lvl = sharedPreferences.getLong("lvl", 1);

    robotPrices[0] = new BigInteger(sharedPreferences.getString("rbt1price", "100"));
    robotPrices[1] = new BigInteger(sharedPreferences.getString("rbt2price", "1100"));
    robotPrices[2] = new BigInteger(sharedPreferences.getString("rbt3price", "12000"));
    robotPrices[3] = new BigInteger(sharedPreferences.getString("rbt4price", "130000"));
    robotPrices[4] = new BigInteger(sharedPreferences.getString("rbt5price", "1400000"));
    robotQu[0] = new BigInteger(sharedPreferences.getString("rbt1qu", "0"));
    robotQu[1] = new BigInteger(sharedPreferences.getString("rbt2qu", "0"));
    robotQu[2] = new BigInteger(sharedPreferences.getString("rbt3qu", "0"));
    robotQu[3] = new BigInteger(sharedPreferences.getString("rbt4qu", "0"));
    robotQu[4] = new BigInteger(sharedPreferences.getString("rbt5qu", "0"));
}

修改 这也行不通:

robotPrices[0] = new BigInteger(sharedPreferences.getLong("rbt1price", 100));

2 个答案:

答案 0 :(得分:2)

来自https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String, java.lang.String)

  

如果存在此名称不是String的首选项,则抛出ClassCastException。

您似乎应该使用getLong()而不是getString()。

答案 1 :(得分:1)

好的,我发现它在android studio(或java编译器)中有点像bug。我只需要添加
String rp0 = sharedPreferences.getString("rbt1price", "100");
一切正常。所以,我没有像有些人告诉我的那样违反了Java的规则"。 谢谢你的回答!