【问题标题】:how can I write the new value in shared preference [duplicate]如何在共享首选项中写入新值[重复]
【发布时间】:2014-06-14 03:20:54
【问题描述】:

我在与 B 运行计算后共享了偏好值 A,您可以通过将 A 替换为新值直接将 AB 的结果写入共享偏好中

public class Stats extends Activity {
private final static String MY_PREFERENCES = "MyPref";
private final static String GIORNISPETT = "giornispett";    
public void indietro (View view){
}
@Override
public void onCreate(Bundle savedInstanceState) {
    SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
    int giornispett = Integer.parseInt(prefs.getString(GIORNISPETT, "24"));

    super.onCreate(savedInstanceState);
    setContentView(R.layout.stats);

    Intent intent=getIntent();
    String trn=getPackageName();
    int Giorni=intent.getIntExtra(trn+".Intgiorni", 0);
    int Giorniresidui=giornispett-Giorni;


    TextView tvgiorni=(TextView)findViewById(R.id.txtgiorni);        
    tvgiorni.append(+Giorni+"");


    TextView tvGiorni_rest=(TextView)findViewById(R.id.txtGiorni_rest);        
    tvGiorni_rest.setText(""+Giorniresidue);



}

}

【问题讨论】:

  • 已经有多个问题在问这个问题,一个简单的谷歌就会返回许多基本示例和教程。请在发布新问题之前进行一些研究。

标签: android sharedpreferences


【解决方案1】:

最简单的方法是使用SharedPreferences.Editor API 和一组put API:

//update application settings based on check box state
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activityContext);
Editor editor = sharedPrefs.edit();
editor.putBoolean("optionName", !checkBox.isChecked());
editor.commit();

【讨论】:

  • 我试过了,但我不知道怎么放
  • 要为应用程序 sharedPreferences 赋予一些价值,您必须使用 Editor,而要激活编辑器,只需使用 edit() API。而不是使用 Editor.commit() API 存储您的更改(例如,请参阅 developer.android.com/reference/android/content/…,布尔值)。
【解决方案2】:

向共享首选项添加值在键值模式下工作。如果您两次使用相同的键,第一个值将被覆盖。

【讨论】:

  • 好的,解决了,谢谢大家。
【解决方案3】:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.put("key", value);
editor.commit();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2019-05-11
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多