jBob jBob - 1 year ago 88
Java Question

Android writing class to internal storage

So I'm making a weather app and I found when the app is idle for too long and destroyed that the forecast data is lost. So I think the best solution is to save the data to internal storage and retrieve it when it's needed.

The class containing the data has 2 arrays of other data classes, and it all contains strings, ints and doubles.

What is the best way to save this data? The options I've seen are a preferences file or saving it to a file in local storage.

I didn't think the preferences file would work because it sounds like that is more meant for smaller amounts of data.

I've been trying to save to local storage, but that hasn't been going well. Not too familiar with manually saving bytes to a file, and the Android developer guides aren't very comprehensive at all. I tried to serialize it, but get the not serializeable error. As far as writing the bytes I think I got it correctly written by converting strings to bytes using getBytes, saving the ints as they are, and converting doubles to strings then using getBytes. I'm not sure if that is even the correct way to do it, and I'm not sure how to read the bytes because you have to read a specific number of them. Do I have to find out how many bytes each type of data is going to be? For example finding the type of string encoding and reading the number of bytes for that data type?

What would be the best way of going about this? Should I just use the preferences file? Can someone either tell me how or point me to a resource for reading data from a file like this? Any help would be appreciated.

Answer Source

I tend to use preferences for different amounts of data. Shared preferences save to an xml file. Here is an example:

SharedPreferences.Editor editor = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE).edit();
editor.putString("name", value);
... // add all your other items here to save

To get the data just do something like this:

SharedPreferences preference = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
preference.getString("name", defaultValue);

It is pretty simple and easy to use. I do sometimes save large data sets. For those, I will usually convert the data to json and then save that json as a string. When I get the data I will convert from json to java.

Another option is to use a sqlite database and store all your data there. There are many tutorials and documentation on how to save to a database.

Here is a great read to get you started: https://developer.android.com/guide/topics/data/data-storage.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download