简体   繁体   中英

What is the most efficient way to store an array in SharedPreferences in Android?

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)?

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));

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM