0

I'm developing an android app that gets some data from my API when starts, and it must keep this data during all lifetime. This data may be accessible from any component in the application, so I had always resolved that with a singleton initialized on my Application class. However, singletons are difficult to test so I'm thinking about an alternative. The data shouldn't be stored in shared preferences, as they will be get each time the application opens so, what would you do? Does a singleton is the best option here?

Thanks in advance

FVod
  • 2,245
  • 5
  • 25
  • 52

1 Answers1

0

What kind of data is it?

If it fits your needs, and you're storing some kind of records, the preferred way is to use SQLiteDatabase for ease of querying and writing to.

If its just some kind of preferences, I would use SharedPreferences myself, but if its out of the table, you can simply write the data to a file which path you can resolve using Environment.getExternalStorageDirectory() given that one is available, and if not, you can fall back on Context.getFilesDir()

in following fashion forexample..

BufferedWriter bw = new BufferedWriter(new FileWriter(new File(mContext.getFilesDir(), "prefs.dat")));
bw.write(data);
bw.close();

and read it back in similar way

BufferedReader br = new BufferedReader(new FileReader(new File(mContext.getFilesDir(), "prefs.dat")));
data = br.readLine();
br.close();

and on the way you can serialize the data to a better format than plaintext, such as JSON.

Pasi Matalamäki
  • 1,843
  • 17
  • 14
  • Thanks for your answer. The data is some basic models such as an array of genres, the current user, etc. I was thinking not to use the SharedPreference because, if I use shared preferences, then when the app is restarted that data is still alive, and my data needs to be recreated each time the app starts. However, I can still use sharedpreferences and recreate them when the app starts or I can use a singleton, I doubt about which option is the best – FVod Aug 19 '16 at 11:17