首选项上的保存位置始终为空

Saved Location on Preferance is allways null

我尝试在我的首选项中保存一个位置。 SavedLocation class 存储三个变量:名称、位置和位置类型。在我尝试从首选项中读取保存的日期之前,一切看起来都很棒。名称和位置类型已完美存储,但存储位置为空。在调试中,保存位置包含所有需要的变量,但看起来像 ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType)); 没有写正确我的日期。

private void saveLocation(SavedLocation savedlocation, Context context) {
    Gson gson = new Gson();
    Type savedLocationsType = new TypeToken<ArrayList<SavedLocation>>() {}.getType();
    ArrayList<SavedLocation> savedLocations = getSavedLocations(context);
    savedLocations.add(savedlocation);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor ed = prefs.edit();
    ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
    ed.apply();
}

SavedLocation class 相似:

 public SavedLocation(String name, Location location, LocationType type) {
    this.name = name;
    this.location = location;
    this.type = type;
}

有什么建议吗?

试试这个

SharedPreferencesEditor 创建变量。

  SharedPreferences pref;
  Editor editor;
  String PREF_NAME="my_location"

现在获得优先权

    pref = this.getSharedPreferences(PREF_NAME, 0);
    editor = pref.edit();

现在将位置添加到 preference

  editor.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
    editor.commit();

然后获取数据

  String location=pref.getString(savedLocations, "defaultvalue");