0

I keep getting this error message

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

I am trying to pass a long value between activities using shared preferences here is the code for my first activity

SharedPreferences sp = getApplicationContext().getSharedPreferences("userdata", Context.MODE_PRIVATE);
Calendar cal = Calendar.getInstance();
SharedPreferences.Editor editor = sp.edit();

editor.putLong("time"+i, cal.getTimeInMillis());
editor.commit();

here is my code for the second activity.

ArrayList<Long> time         = new ArrayList<Long>();
sp = getSharedPreferences("userdata", Context.MODE_PRIVATE);
time.add(sp.getLong("time"+i,0)); // here is where the error occurs

The reason for the +i at the end of "time" is that these put and receive messages are running in for loops, because there are multiple longs that are being passed and the order matters. Please let me know if there is another way I should do this or how to resolve this exception.

Thank You

  • Use putString() instead of putLong(),if you want to store just as String.And also change ArrayList type to String. – androidLearner Jun 30 '21 at 16:31
  • I don't think the OP does want to store a string @androidLearner, they want to store a long as they've attempted in the question. – Henry Twist Jun 30 '21 at 16:36
  • 3
    You must have put a string with the same key (`"time" + i`) somewhere, if this was done beforehand during testing, maybe clear the app data if that's the case? – Henry Twist Jun 30 '21 at 16:37
  • I still need it as a long for comparison in an if statement should I cast is or use the Long class's method? – Ranger 4860 Jun 30 '21 at 16:40
  • 1
    Yes I cleared the app data and now I am no longer getting an exception. Thank You – Ranger 4860 Jun 30 '21 at 16:44
  • Great, as a side note this might not be the best way to pass data to an activity unless you actually need it to be persistent. – Henry Twist Jun 30 '21 at 16:48
  • this variable will be updated about twice a day and I will be using the same format except editor.apply(); to save changes. – Ranger 4860 Jun 30 '21 at 16:53

0 Answers0