I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?


当前回答

public class VcareSharedPreference {
  private static VcareSharedPreference sharePref = new VcareSharedPreference(); 
  private static SharedPreferences sharedPreferences; 
  private static SharedPreferences.Editor editor;
  private VcareSharedPreference() {
 } 
public static VcareSharedPreference getInstance(Context context) {
    if (sharedPreferences == null) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    return sharePref;
 }
public void save(String KEY, String text) {
    editor.putString(KEY, text);
    editor.commit();
}
 public String getValue(String PREFKEY) {
    String text;

    //settings = PreferenceManager.getDefaultSharedPreferences(context);
    text = sharedPreferences.getString(PREFKEY, null);
    return text;
}
public void removeValue(String KEY) {
    editor.remove(KEY);
    editor.commit();
}

public void clearAll() {
    editor.clear();
    editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
    Gson gson = new Gson();
    String json = gson.toJson(modelCourses);
    editor.putString(key, json);
    editor.apply();
}

public ArrayList<ModelWelcome> getArray(String key) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString(key, null);
    Type type = new TypeToken<ArrayList<ModelWelcome>>() {
    }.getType();
 return gson.fromJson(json, type);}}

其他回答

使用Kotlin,对于简单的数组和列表,你可以这样做:

class MyPrefs(context: Context) {
    val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
    var listOfFloats: List<Float>
        get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
        set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}

然后轻松访问首选项:

MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats

您可以将其转换为Map Object来存储它,然后在检索SharedPreferences时将值更改回ArrayList。

public class VcareSharedPreference {
  private static VcareSharedPreference sharePref = new VcareSharedPreference(); 
  private static SharedPreferences sharedPreferences; 
  private static SharedPreferences.Editor editor;
  private VcareSharedPreference() {
 } 
public static VcareSharedPreference getInstance(Context context) {
    if (sharedPreferences == null) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    return sharePref;
 }
public void save(String KEY, String text) {
    editor.putString(KEY, text);
    editor.commit();
}
 public String getValue(String PREFKEY) {
    String text;

    //settings = PreferenceManager.getDefaultSharedPreferences(context);
    text = sharedPreferences.getString(PREFKEY, null);
    return text;
}
public void removeValue(String KEY) {
    editor.remove(KEY);
    editor.commit();
}

public void clearAll() {
    editor.clear();
    editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
    Gson gson = new Gson();
    String json = gson.toJson(modelCourses);
    editor.putString(key, json);
    editor.apply();
}

public ArrayList<ModelWelcome> getArray(String key) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString(key, null);
    Type type = new TypeToken<ArrayList<ModelWelcome>>() {
    }.getType();
 return gson.fromJson(json, type);}}

为什么不把数组列表放在应用程序类上呢?它只有在应用被杀死时才会被销毁,所以,只要应用可用,它就会一直存在。

以防有人需要保存列表的列表,即list < list < String > >。我是这样做的:

序列化

Gson gson = new Gson();
// Save the size of the array
sharedPreferencesEditor.putInt("ArraySize", myArray.size());

for (int i=0; i<myArray.size(); i++) {
  String key = "Array"+i;
  String json = gson.toJson(myArray.get(i));
  sharedPreferencesEditor.putString(key, json);
}

sharedPreferencesEditor.commit();

反序列化

// Get the size of the array to be deserialized. In my case, the default number should be 3
int arraySize = sharedPreferences.getInt("ArraySize",3);

myArray = new ArrayList<List<String>>();

for (int i=0; i<arraySize; i++) {
  String key = "Array"+i;
  String json = sharedPreferences.getString(key, null);
  List<String> arrayTemp= gson.fromJson(json, List.class);
  myArray.add(arrayTemp);
}

// My array may also include components with empty strings. 
// Gson makes them null values and it is not possible 
// to deserialize them as empty strings. 
// The following takes care of that:

for (int i=0; i<myArray.size();i++) {
   if (myArray.get(i) == null) {
      List<String> emptyComponent = new ArrayList<String>() {
         { add(""); }
      };
      myArray.set(i,emptyComponent);
   }
}