public interface
SharedPreferences
android.content.SharedPreferences |
Class Overview
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int)
.
//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(){
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public 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(){@Overridepublic 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