应该保存天气的共享偏好数据,不显示在已添加书签的活动中

时间:2018-05-12 13:52:11

标签: android sharedpreferences

///我已经尝试制作天气应用程序,它功能齐全,但是,我已经实现了代码并且数据确实保存,因为logcat中没有错误,但是,当我查看带有书签的活动时保存的天气位置不存在。是否有任何可以帮助我

公共类SaveData {

private static final String TAG ="SaveData";
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;

private static String prefName = "Pref";
public static ArrayList<HistoryObj> weatherHistoryList = new ArrayList<>();
//KEYS to store
public static String WEATHER_LIST_KEY= "WeatherIds";

public SaveData(Context context){
    int PRIVATE_MODE = 0;
    this.context = context;
    preferences = context.getSharedPreferences(prefName,PRIVATE_MODE);
    editor = preferences.edit();

    // TinyDb is class to simplify storage of ArrayList in Shared Preferences
    // getting book marked list from storage
    weatherHistoryList = getWeatherList();


}


    public ArrayList<HistoryObj> getWeatherList(){
    Gson gson = new Gson();

    ArrayList<String> objStrings = getListString(WEATHER_LIST_KEY);
    ArrayList<HistoryObj> objects =  new ArrayList<HistoryObj>();

    for(String jObjString : objStrings){
        HistoryObj value  = gson.fromJson(jObjString,  HistoryObj.class);
        objects.add(value);
    }

    return objects;
}


public void saveWeatherList(ArrayList<HistoryObj> objArray){
    checkForNullKey(WEATHER_LIST_KEY);
    Gson gson = new Gson();
    ArrayList<String> objStrings = new ArrayList<String>();
    for(HistoryObj obj : objArray){
        objStrings.add(gson.toJson(obj));
    }
    putListString(WEATHER_LIST_KEY, objStrings);
}

public ArrayList<String> getListString(String key) {
    return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}

public void putListString(String key, ArrayList<String> stringList) {
    checkForNullKey(key);
    String[] myStringList = stringList.toArray(new String[stringList.size()]);
    preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}

public void checkForNullKey(String key){
    if (key == null){
        throw new NullPointerException();
    }
}

}

0 个答案:

没有答案