ITEEDU

SharedPreferences--简单数据存储

SharedPreferences是将数据以XML文件形式放在手机里,在DDMS中的File Explorer中展开到/data/data/应用程序的包路径/share_prefs/SETTING_Infos.xml

用法:

SharedPreferences settings = getSharedPreferences(文件名, 0); 
String name = settings.getString(键名, 默认值); 

还可以get其它类型

SharedPreferences settings = getSharedPreferences(文件名, 0);
settings.edit()
			.putString(键名, 值)
			.putString(键名, 值)
			.commit();

下例:在退出时保存内容,打开程序时载入。

public class MainActivity extends Activity {
	public static final String SETTING_INFOS = "SETTING_Infos";
	public static final String NAME = "NAME";
	public static final String PASSWORD = "PASSWORD";
	private EditText field_name;
	private EditText filed_pass;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Find VIew
        field_name = (EditText) findViewById(R.id.name);
        filed_pass = (EditText) findViewById(R.id.password);
        // Restore preferences
        SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
		String name = settings.getString(NAME, "");
		String password = settings.getString(PASSWORD, "");
		//Set value
		field_name.setText(name);
		filed_pass.setText(password);

    }
    
    @Override
    protected void onStop(){
        super.onStop();
		SharedPreferences settings = getSharedPreferences(SETTING_INFOS, 0);
		settings.edit()
			.putString(NAME, field_name.getText().toString())
			.putString(PASSWORD, filed_pass.getText().toString())
			.commit();
    }
}