package com.test.storage;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class SharePreferenceDemo extends Activity{
private TextView et_name;
private TextView et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("info",MODE_PRIVATE);
//獲取數據 第一個參數爲存儲的字符串的值,第二個參數是設置沒取到對應的數據時,默認顯示的值
String name = sp.getString("name", "");
String password = sp.getString("password", "");
et_name = (TextView) this.findViewById(R.id.name);
et_password = (TextView) this.findViewById(R.id.password);
et_name.setText(name);
et_password.setText(password);
}
public void click(View v){
//路徑在data/data/程序標示包名/shared_prefs/
//不用爲文件添加後綴名,添加也是無效的.數據是保存在xml中。
String name = et_name.getText().toString().trim();
String password = et_password.getText().toString().trim();
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
//獲取sp的編輯器
Editor editer = sp.edit();
//通過編輯器存放數據
editer.putString("name", name);
editer.putString("password", password);
//提交,保存的數據需要提交才能生效。
editer.commit();
}
}