Android 如何将对象的ArrayList添加到SharedReferences中

Android 如何将对象的ArrayList添加到SharedReferences中,android,arraylist,sharedpreferences,android-storage,Android,Arraylist,Sharedpreferences,Android Storage,我创建了一个ArrayList,其中包含一个类的对象。在完成将所有对象插入该数组列表后,如何将该数组列表推送到共享首选项中 模型类: public class Weather { private double minTemp, maxTemp, humidity, windSpeed; private String date, desc; public String getDate() { return date; } public vo

我创建了一个ArrayList,其中包含一个类的对象。在完成将所有对象插入该数组列表后,如何将该数组列表推送到共享首选项中

模型类:

public class Weather {
    private double minTemp, maxTemp, humidity, windSpeed;
    private String date, desc;

    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }

    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }

    public double getMinTemp() {
        return minTemp;
    }
    public void setMinTemp(double minTemp) {
        this.minTemp = minTemp;
    }

    public double getMaxTemp() {
        return maxTemp;
    }
    public void setMaxTemp(double maxTemp) {
        this.maxTemp = maxTemp;
    }

    public double getHumidity() {
        return humidity;
    }
    public void setHumidity(double humidity) {
        this.humidity = humidity;
    }

    public double getWindSpeed() {
        return windSpeed;
    }
    public void setWindSpeed(double windSpeed) {
        this.windSpeed = windSpeed;
    }
}
ArrayList创建:

ArrayList<Weather> weatherArr = new ArrayList<Weather>();

for(....){
  Weather weather = new Weather();
  weather.setDate(date);
  weather.setDesc(description);
  weather.setMinTemp(minTemp);
  weather.setMaxTemp(maxTemp);
  weather.setHumidity(humidity);
  weather.setWindSpeed(windSpeed);
  weatherArr.add(weather);
}

现在,如何将此ArrayList(weatherArr)插入到SharedReferences(WeatherSharedReferences)中?

我有一个窍门给你。将Gson添加到依赖项中

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.code.gson:gson:2.2.4'
}
将对象转换为Json并保存为字符串形式的SharedPrefs

String data = new Gson().toJson(weatherArr)
需要时将其从字符串转换回字符串

List<Weather> data = new Gson(stringData, new TypeToken<List<Weather>>(){}.getType()).
List data=new Gson(stringData,new-TypeToken(){}.getType())。

我在这里找到了一些东西,但这可能比使用第三方LIB更棘手,因为答案是:你不能。共享PREF用于原始数据类型:考虑数据库或文件存储。转到此链接..当您将object Weather的ArrayList转换为名为“data”的字符串时,我需要从该字符串返回object Weather的ArrayList,而不是单个Weather类。如何做到这一点?您可以使用TypeToken-newTypeToken(){}.getType()
List<Weather> data = new Gson(stringData, new TypeToken<List<Weather>>(){}.getType()).