Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SharedPreferences data size, Is it possible?

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.

like image 747
Batuhan Coşkun Avatar asked Nov 17 '25 16:11

Batuhan Coşkun


1 Answers

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;
like image 51
Andy Res Avatar answered Nov 20 '25 06:11

Andy Res