0

I need to store an array in shared prefs without the use of external libs like Prefser or Hawk. Which I tried and found a lot of problems with both of them.

So my search led me to two different methods:

  1. Using Sets:

    //Set the values
    Set<String> set = new HashSet<String>();
    set.addAll(listOfExistingScores);
    scoreEditor.putStringSet("key", set);
    scoreEditor.commit();
    
    //Retrieve the values
    Set<String> set = myScores.getStringSet("key", null);
    
  2. Using String manipulation:

    //Set the values
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < playlists.length; i++) {
        sb.append(playlists[i]).append(",");
    }
    prefsEditor.putString(PLAYLISTS, sb.toString());
    
    //Retrieve the values
    String[] playlists = playlist.split(",");
    

The question: What would be a more efficient way to do it when the order of the items does not matter and I have a big amount of items (say > 300)?

halfer
  • 19,824
  • 17
  • 99
  • 186
Emil Adz
  • 40,709
  • 36
  • 140
  • 187
  • 1
    why aren't you using a DB? I normally don't use SharedPreferences for keys more than 30 – gmetax Sep 25 '17 at 09:05
  • @gmetax, you are right, usually, that's what I do also. But in this case, this is the only thing that I need to store and I didn't want to mess with DB implementation just for one single ArrayList. – Emil Adz Sep 25 '17 at 09:06
  • 1
    I can't find the limit store of SharedPreferences but I don't believe that will be a good practice to store more than 1000 values on SharedPreferences – gmetax Sep 25 '17 at 09:08
  • 1
    check that also https://stackoverflow.com/a/43080499/2401265 – gmetax Sep 25 '17 at 09:09
  • @EmilAdz, make a JSONArray and store it into SharedPreferences. – Maddy Sep 25 '17 at 09:11
  • Actually SharedPreferences stored data in `xml` file then you put one key but >1000 value (although value contracted only one value). So key-value SharedPreference has no meaning. Have you considered using `file` to store your over 1000 value array? – CoXier Sep 25 '17 at 09:11
  • Why not to try Realm? But i must say you need to read documents and spend time on it to figure it out how great it is. – Emre Aktürk Sep 25 '17 at 09:11
  • @gmetax, I understand where you are going with it, but like I said for the sake of this argument lets say that I have 500 items and they will never exceed the storage limit. What would be a better way to store them in the SP without a DB. – Emil Adz Sep 25 '17 at 09:12
  • @EmreAktürk, Like I said in the question I prefer not to use external libs at this stage. – Emil Adz Sep 25 '17 at 09:14
  • then I believe the best option is 2. Even though that you will need time on 2 loops, I believe also on the core android will happen the same with `set` to be saved on the `xml` file of the `SharedPreferences`. – gmetax Sep 25 '17 at 09:16
  • @Maddy, what is the difference between doing that and using a single string with manipulations, from an efficiency standpoint? – Emil Adz Sep 25 '17 at 09:18
  • JSONArray will not be more efficient, but it would be "easier" to manipulate and readable – gmetax Sep 25 '17 at 09:22
  • 1
    @EmilAdz, This is not an efficient solution, this is just a way to do your stuff. Even storing that much data in SharedPreferences will never be efficient. – Maddy Sep 25 '17 at 09:22
  • Why dot directly use `File` ? – CoXier Sep 25 '17 at 09:35

2 Answers2

0

The most efficient way would be store in a string via a ObjectSeializer.

A striing would loose the order of data but ObjectSerializer will remeber it. Here is a ObjectSerializer you can use:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerializer {


public static String serialize(Serializable obj) throws IOException {
    if (obj == null) return "";
    try {
        ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
        objStream.writeObject(obj);
        objStream.close();
        return encodeBytes(serialObj.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static Object deserialize(String str) throws IOException {
    if (str == null || str.length() == 0) return null;
    try {
        ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
        ObjectInputStream objStream = new ObjectInputStream(serialObj);
        return objStream.readObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static String encodeBytes(byte[] bytes) {
    StringBuffer strBuf = new StringBuffer();

    for (int i = 0; i < bytes.length; i++) {
        strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
        strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
    }

    return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length(); i+=2) {
        char c = str.charAt(i);
        bytes[i/2] = (byte) ((c - 'a') << 4);
        c = str.charAt(i+1);
        bytes[i/2] += (c - 'a');
    }
    return bytes;
}

}

and call via:

sharedpref.putString("data",ObjectSerializer.serialize(array1));
  • Why would using a string will lose the order? You are running on the array in order and appending items in order, split with save the order in which you appended the items. – Emil Adz Sep 25 '17 at 09:20
0

JsonArray helps you to convert and store

public static void putStringArray(Context context, String key, String[] array) {
    if (context == null) {
        return;
    }
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    JSONArray mJSONArray = new JSONArray(Arrays.asList(array));
    editor.putString(key, String.valueOf(mJSONArray));
    editor.apply();
}

public static String[] getStringArray(String key, Context context) {
    if (context == null) {
        return null;
    }
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    String[] stringArray = new String[0];
    try {
        JSONArray jsonArray = new JSONArray(prefs.getString(key, ""));
        int len = jsonArray.length();
        stringArray = new String[len];

        for (int i = 0; i < len; i++) {
            try {
                stringArray[i] = jsonArray.getString(i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return stringArray;
}
MilapTank
  • 9,988
  • 7
  • 38
  • 53