I want to save some cache data for my appliaction. I used to do this by saving the data in the external storage and this worked fine. But I want my device to show my cache size in the app settings but It doesn´t. I guess this is because I save the data in external storage. What I want is that my data still exists aufter closing the app or even swichen off my device. Now I tried to save my files in the internal storage but I have troubles reading the files + the cache size is still wrong in settings. Can anyone give me the methodes do write and read strings into files in the applications cache please?
Read Cache – the cache services requests for read I/O only. If the data isn't in the cache, it is read from persistent storage (also known as the backing store). Write Cache – all new data is written to the cache before a subsequent offload to persistent media.
I think everything is clearly explained here... :)
if you have juste simple data, you can use SharedPreferences like this for example :
public static void writeString(Context context, final String KEY, String property) {
SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY, context.MODE_PRIVATE).edit();
editor.putString(KEY, property);
editor.commit();
}
public static String readString(Context context, final String KEY) {
return context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY, context.MODE_PRIVATE).getString(KEY, null);
}
in order to use the cache, you have to use the method
File file = new File(context.getCacheDir(), filename);
which return a File object you can write and read on.
Use this to write :
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Be aware that Android may delete this file if the system lack space, so don't use this to store too much data. ( > 1MB)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With