如何在共享首选项中编写新值

时间:2014-04-28 14:14:52

标签: android sharedpreferences

在使用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);



}

}

3 个答案:

答案 0 :(得分:1)

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.put("key", value);
editor.commit();

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用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();