如何将Object的ArrayList添加到SharedPreferences中

时间:2017-01-12 12:55:03

标签: android arraylist sharedpreferences android-storage

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

Model类:

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 Creation:

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

1 个答案:

答案 0 :(得分:4)

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

repositories {
    mavenCentral()
}

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

将您的对象转换为Json并以String形式保存到SharedPrefs。

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

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

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