android - 如何知道Android SharedPreferences保存成功?

标签 android sharedpreferences

我正在将一些数据从 fragment 保存到 SharedPreference,并希望在其他 fragment 中使用这些数据。但我只想在成功保存 SharedPreferences 时执行 fragment 事务,否则,其他 fragment 将无法检索数据(因为使用这些 SharedPreference 值来检索数据)。

我的代码:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

  ... ... ... ... ... ... ... ... ...

  public void setSharedPref(String key, String val) {
      SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPref.edit();
      editor.putString(key, val);
      editor.commit();

  }

  public String fetchSharedPref(String key) {
      SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
      String val = sharedPref.getString(key, Constant.SHARED_PREF_DEFAULT_MSN);
      return val;
  }
}

如何确定SharedPreferences保存成功?
有什么方法可以实现只有在 SharedPreferences 保存成功时才会调用的回调?

最佳答案

来自 docs .

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

然后去检查commit()方法here .

Return type: boolean

Description: Returns true if the new values were successfully written to persistent storage.

关于android - 如何知道Android SharedPreferences保存成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43631942/

相关文章:

android - 单击后如何在另一个 ListView 中显示 ListView

android - 需要一些关于开发者控制台上的 beta/alpha 测试的说明

java - 安卓 :shared preference in jni

java - 使用警报编辑 SharedPreferences

android - 从多个 Activity 中调用共享首选项,并访问其中一个中的按钮

android - recyclerview 上方的 fragment 未显示

java - 开始 Activity 但在后台

android - 使用 sharedpreferences 在 android 中进行 session 管理

android - 当我回到上一个 Activity 时 SnackBar 仍然显示