持久化技術(shù)SharedPreferences存儲(chǔ)
掃描二維碼
隨時(shí)隨地手機(jī)看文章
public interface SharedPreferences android.content.SharedPreferences Class Overview
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int).
1、調(diào)用SharedPreferences對(duì)象的edit()方法獲得SharedPreferences.Editor對(duì)象:
//Editor?android.content.SharedPreferences.edit()
SharedPreferences.Editor?mEditor?=?getSharedPreferences("data",MODE_PRIVATE).edit();文件名為data,mode為MODE_PRIVATE。 2、向SharedPreferences.Editor對(duì)象中添加數(shù)據(jù):
mEditor.putBoolean("boolean",?true);
mEditor.putFloat("float",?0.01F);
mEditor.putString("String",?"a?string");3、調(diào)用commit()將數(shù)據(jù)提交,完成數(shù)據(jù)存儲(chǔ)
mEditor.commit();
存儲(chǔ)和獲取存儲(chǔ)數(shù)據(jù)部分代碼:
Button?mButton?=?(Button)findViewById(R.id.save);
mButton.setOnClickListener(new?OnClickListener(){@Overridepublic?void?onClick(View?view){
//Editor?android.content.SharedPreferences.edit()
SharedPreferences.Editor?mEditor?=?getSharedPreferences("data",MODE_PRIVATE).edit();
mEditor.putBoolean("boolean",?true);
mEditor.putFloat("float",?0.01F);
mEditor.putString("String",?"a?string");
mEditor.commit();
}
});
Button?getButton?=?(Button)findViewById(R.id.get);
getButton.setOnClickListener(new?OnClickListener(){
@Override
public?void?onClick(View?view){
//SharedPreferences?android.content.ContextWrapper.getSharedPreferences(String?name,?int?mode)
SharedPreferences?mSharedPreferences?=?getSharedPreferences("data",MODE_PRIVATE);
boolean?boolStr?=?mSharedPreferences.getBoolean("boolean",?false);
float?floatStr?=?mSharedPreferences.getFloat("float",?0.0f);
String?str?=?mSharedPreferences.getString("String",?"str");
TextView?tv?=?(TextView)findViewById(R.id.tv);
tv.setText("?str?is:?"+str?+"n"+?"?boolean?is?:"+?boolStr?+"n"+"?float?is:?"+?floatStr?);
}
});
用SharedPreferences實(shí)現(xiàn)記住密碼功能:
完整代碼在:https://github.com/HiSunny/ComeOnSharedPreferences.git





