位于android.content目录下的
SharedPreferences
| android.content.SharedPreferences |
Class Overview
Interface for accessing and modifying preference data returned by . For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get
methods must be treated as immutable by the application.
To write values:
- Call
[edit()]
to get a `[SharedPreferences.Editor] - Add values with methods such as
[putBoolean()] and [putString()]
. - Commit the new values with
[commit()]
To read values, use [SharedPreferences]
methods such as [getBoolean()]
and [getString()]
.
Here is an example that saves a preference for silent keypress mode in a calculator:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
sp存储的目录:data/data下 包名 下 shared_prefs 下的一个XML文件 存储方式是键值对
image.png
public class MainActivity extends Activity {
private EditText et_input;//输入的文本
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化视图
initView();
//回显操作
reShow();
}
/**
* 回显操作
*/
private void reShow() {
//从sp中取数据
String con = sp.getString("content", "");
et_input.setText(con);
}
/**
* 初始化视图
*/
private void initView() {
et_input = (EditText) findViewById(R.id.et_input);
//实例化sp
sp = getSharedPreferences("config.xml", 0);
}
/**
* 点击保存数据
* @param v
*/
@SuppressLint({ "NewApi", "ShowToast" })
public void clickSave(View v) {
// System.out.println("按钮被点击了");
//拿到文本内容
String et_con = et_input.getText().toString().trim();
if (et_con.isEmpty()) {
Toast.makeText(MainActivity.this, "请输入文本内容", 0).show();
return;
}
//保存数据到sp
Editor edit = sp.edit();
edit.putString("content", et_con);
//提交
edit.commit();
System.out.println("保存数据成功");
}
}
网友评论