SharePrefreference只支持存储boolean,int,float,long,String类型数据,不支持条件查询,不能完全替代数据库
MainActivity.class
public classMainActivityextendsAppCompatActivity {
static finalStringKEY="MyValue";
privateEditTextet;
SharedPreferencespreferences;
SharedPreferences.Editoreditor;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editor=preferences.edit();
et= (EditText) findViewById(R.id.editText);
findViewById(R.id.readBtn).setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
String in =preferences.getString(KEY,"d当前数值不存在");
Toast.makeText(getApplicationContext(),in,Toast.LENGTH_LONG).show();
}
});
findViewById(R.id.wirBtn).setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
editor.putString(KEY,et.getText().toString());
if(editor.commit()){
Toast.makeText(getApplicationContext(),"写入成功",Toast.LENGTH_LONG).show();
}
}
});
activity_main:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"/>
<Button
android:layout_below="@+id/btn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入"
android:id="@+id/wirBtn"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取"
android:id="@+id/readBtn"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:layout_marginRight="51dp"
android:layout_marginEnd="51dp"/>
效果:
网友评论