Antoni Simka Antoni Simka - 1 month ago 14
Java Question

Java long cannot be cast to string

I've created a program that saves and loads BigInteger and String variables. When I've started the program it shows that exception:


java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String


And it says it happens here:

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


My saving method:

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();
}


My loading method:

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"));
}


Edit:
THIS doesn't work too:

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

Answer Source

Ok, I've found it was kind of bug in android studio (or java compiler). I just needed to add
String rp0 = sharedPreferences.getString("rbt1price", "100");
and everything works. So, I did not, as some told me, "violate java's rules". Thanks for answers!