持久化技術SharedPreferences存儲
public interface SharedPreferences android.content.SharedPreferences Class Overview
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int)
.
1、調(diào)用SharedPreferences對象的edit()方法獲得SharedPreferences.Editor對象:
//Editor?android.content.SharedPreferences.edit() SharedPreferences.Editor?mEditor?=?getSharedPreferences("data",MODE_PRIVATE).edit();
文件名為data,mode為MODE_PRIVATE。 2、向SharedPreferences.Editor對象中添加數(shù)據(jù):
mEditor.putBoolean("boolean",?true); mEditor.putFloat("float",?0.01F); mEditor.putString("String",?"a?string");
3、調(diào)用commit()將數(shù)據(jù)提交,完成數(shù)據(jù)存儲
mEditor.commit();
存儲和獲取存儲數(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實現(xiàn)記住密碼功能:
完整代碼在:https://github.com/HiSunny/ComeOnSharedPreferences.git