Android 中SharedPreferences使用
一、SharedPreferences使用1
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPerferences = PreferenceManager.getDefaultSharedPreferences(
this
);
int
counter = mPerferences.getInt(
"counter"
,
1
);
TextView mTextView = (TextView)findViewById(R.id.showMssage);
mTextView.setText(
"Counter is :"
+ counter);
Editor mEditor = mPerferences.edit();
mEditor.putInt(
"counter"
, ++counter);
mEditor.commit();
}
|
mEditor.putInt("counter", ++counter); 为写入counter的值为++counter,最后提交。
int counter = mPerferences.getInt("counter", 1); 获取写入couter的值,默认为1.
二. 下面会创建SPF.xml文件 并将数据写入xml文件中,最后读取xml中的数据。
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
this
.getSharedPreferences(
"SPF"
,MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString(
"name"
,
"张三"
);
editor.putInt(
"age"
,
29
);
editor.putBoolean(
"boy"
,
true
);
editor.commit();
Log.i(
"name"
, sharedPreferences.getString(
"name"
,
"no name"
));
Log.i(
"age"
, Integer.toString(sharedPreferences.getInt(
"age"
,
0
)));
Log.i(
"boy"
, Boolean.toString(sharedPreferences.getBoolean(
"boy"
,
false
)));
}
|
参考:
SharedPreferences用法
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2013/03/14/2958839.html,如需转载请自行联系原作者