-1

I need to store a Class object in SharedPreferences so as to be able to retrieve it on another activity.

Here is the code:

ForecastIO fio = new ForecastIO(apikey);
fio.setUnits(ForecastIO.UNITS_SI);
fio.setLang(ForecastIO.LANG_ENGLISH);
fio.getForecast(""+latif+"",""+longit+"");
FIOCurrently currently = new FIOCurrently(fio); 

How can I store "currently" in a SharedPreferences?

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Donnie Ibiyemi
  • 971
  • 3
  • 15
  • 26
  • @Selvin what do you mean field by field. kindly show an example – Donnie Ibiyemi Dec 10 '14 at 23:46
  • it is ironic, but true, answer as you did not provide any information about the object... anyway you can either serialize it to string or put every primitive field from object – Selvin Dec 10 '14 at 23:50
  • @Selvin ok here is some background info on the object.Its from a forecast.io Libary. You can checkit out in full detail here https://github.com/dvdme/forecastio-lib-java – Donnie Ibiyemi Dec 11 '14 at 00:00
  • What fields from your FIOCurrently object do you want to save on Preferences, exactly? – joao2fast4u Dec 11 '14 at 00:39

2 Answers2

1

You can't store objects in SharedPreferences. Like Selvin said in a comment. You should do it field by field.

For example: if ForecastIO.UNITS_SI equals an int, you can easily store it into SharedPreferences with SharedPreferences.Editor (take a look at the documentation: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html) and the same with the other variables.

However, if you want to pass information through to another activity, I recommend you to use Intent. Then you even send an object to one another however the object MUST be parceable. Take a look at this stackoverflow question: How to send an object from one Android Activity to another using Intents?.

Your desired result is similar to his with a proper answer and comments why you can't just pass objects to another activity without implementing parceable.

Community
  • 1
  • 1
kevto
  • 529
  • 6
  • 15
0

As @kevto says, this is probably not what you should do, but if for some reason you find that you must store the object's state in SharedPreferences, you could serialize it to a Json string using, say, GSon, and then store the string.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67