持久化技术SharedPreferences存储
扫描二维码
随时随地手机看文章
public interface SharedPreferences android.content.SharedPreferences Class Overview
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int)
.
1、调用SharedPreferences对象的edit()方法获得SharedPreferences.Editor对象:
//Editor android.content.SharedPreferences.edit() SharedPreferences.Editor mEditor = getSharedPreferences("data",MODE_PRIVATE).edit();
文件名为data,mode为MODE_PRIVATE。 2、向SharedPreferences.Editor对象中添加数据:
mEditor.putBoolean("boolean", true); mEditor.putFloat("float", 0.01F); mEditor.putString("String", "a string");
3、调用commit()将数据提交,完成数据存储
mEditor.commit();
存储和获取存储数据部分代码:
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实现记住密码功能:
完整代码在:https://github.com/HiSunny/ComeOnSharedPreferences.git