-2

我创建了一个 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);
}

我的共同偏好:

SharedPreferences weatherSharedpreferences = weatherSharedpreferences = getSharedPreferences(WeatherPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = weatherSharedpreferences.edit();

现在如何将此 ArrayList(weatherArr) 插入 SharedPreferences(weatherSharedpreferences)?

4

1 回答 1

4

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

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.code.gson:gson:2.2.4'
}

将您的对象转换为 Json 并作为字符串保存到 SharedPrefs。

String data = new Gson().toJson(weatherArr)

需要时将其从 String 转换回来。

List<Weather> data = new Gson(stringData, new TypeToken<List<Weather>>(){}.getType()).
于 2017-01-12T12:57:11.410 回答