安卓作业:
使用SharedPreference将姓名和年龄信息保存到文件,然后再读取
1.主要xml文件代码:
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名:"/>
<EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入年龄:"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="写入"/>
<Button
android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取" />
</LinearLayout>
2.java部分代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activit
xingming = (EditText)findViewById(R.id.name);
nianling=(EditText)findViewById(R.id.age);
xieru=(Button)findViewById(R.id.write);
qudu=(Button)findViewById(R.id.read);
xieru.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name=xingming.getText().toString();
String age = nianling.getText().toString();
savaToPrefs(name,age);
//显示
Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
}
private boolean savaToPrefs(String name,String age) {
SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("name",name);
edit.putString("age",age);
edit.apply();
return true;
}
});
duchulai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
readFromprefs();
}
private void readFromprefs() {
SharedPreferences preferences1 =getSharedPreferences("data",MODE_PRIVATE);
String name = preferences1.getString("name","");
String age = preferences1.getString("age","");
Toast.makeText(MainActivity.this,"姓名:"+name+" "+"年龄是:"+age,Toast.LENGTH_LONG).show();
xingming.setText("");
nianling.setText("");
}
});
}
}