I'm using SharedPreferences for saving JSONArray, and then using it when i have no connection to the internet. I should check size of saved data because i don't want any big data. I use clear method for that but i want to be sure about that with controlling size. My functions for saving & loading & clearing ;
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, array.toString());
editor.commit();
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(key, ""));
}
public static void clearPrefs(Context c, String prefName){
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
This functions work properly. There is no problem. But i need one more function which returns the size of all data. I investigated it but could not find any solution. Thanks in advance.
You could convert the string to bytes, and then get the length of bytes:
String data = array.toString();
byte[] byteArray = data.getBytes("UTF-8");
long size = byteArray.length;
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