Preferences

SharedPreferences

这次的作业是利用SharedPreferences将姓名和年龄保存到文件,再读取:
在XML中定义如下:

<EditText
android:id="@+id/ev_userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名:" />
<EditText
android:id="@+id/ev_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入年龄:" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入"
android:textSize="20sp"
android:onClick="onClick" />
<Button
android:id="@+id/btn_login2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取"
android:textSize="20sp"
android:onClick="onClick" />
</LinearLayout>
 <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:id="@+id/tv_text"
    android:text=""/>
</LinearLayout>

接下来用使用SharedPreferenxes保存数据:
1)获取SharedPreferenxes对象,使用getSharedPreferenxes(String name,int mode)方法获取;
2)保存SharedPreferenxes数据,通过Editor对象putXxx方法保存;
3)读取SharedPreferenxes数据,即String name = pref.getString("name",mingzi.getText().toString());

public class MainActivity extends AppCompatActivity {
private Button xieru;
private EditText mima;
private EditText mingzi;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
private Button duqu;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);          mingzi = (EditText)findViewById(R.id.edit1);
    mima=(EditText)findViewById(R.id.edit2);
    pref = getSharedPreferences("xieru",MODE_PRIVATE);
    editor = pref.edit();
    duqu=(Button)findViewById(R.id.duqu);
    xieru=(Button)findViewById(R.id.xieru);
    xieru.setOnClickListener(new View.OnClickListener() {
        @Override
       public void onClick(View v) {
            Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
           editor.putString("name",mingzi.getText().toString());
            editor.putString("password",mima.getText().toString());
            editor.commit();

        }
   });
    duqu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = pref.getString("name",mingzi.getText().toString());
            String password=pref.getString("password",mima.toString());
           Toast.makeText(MainActivity.this,"姓名是"+name+"年龄是:"+password,Toast.LENGTH_LONG).show();
        }
    });
  }

}
posted @ 2017-05-09 22:29  Doranmi  阅读(260)  评论(0编辑  收藏  举报