题目内容
1. 使用SharedPreferences实现数据存储,存储的数据包括,姓名(name),性别(sex),年龄(age),根据 以下提供的基础代码,完成以下功能:添加数据:张三,男,30; 删除key为name的数据,清空数据。public class SPActivity extends AppCompatActivity implements View.OnClickListener {private Button btnAdd, btnDelete, btnClear;private TextView tvData;private SharedPreferences sp;private SharedPreferences.Editor editor;private String name;private int age;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sp);btnAdd = (Button) findViewById(R.id.btn_Add);btnDelete = (Button) findViewById(R.id.btn_Delete);btnClear = (Button) findViewById(R.id.btn_Clear); btnClear.setOnClickListener(this);tvData = (TextView) findViewById(R.id.tvData); btnAdd.setOnClickListener(this);// 实例化SharedPreferences,文件名为 MyFile ,模式为 Context.MODE_PRIVATE(1) ____________________________________________________________// 得到 Editor对象(2) ____________________________________________________________}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_Add://editor 调用 putString添加键为name,值为张三的数据(3) __________________________________________________// editor 调用 putString添加键为 sex,值为 男的数据(4)___________________________________________________// editor 调用 pubInt 添加键为 age,值为30的数据(5)___________________________________________________// editor 调用 apply() 方法提交 数据(6) __________________________________________________name = sp.getString("name", "default");age = sp.getInt("age", 0);// 将姓名,年龄在文本组件 tvData上,调用 setText()方法显示(7) __________________________________________________break;case R.id.btn_Delete:// editor 调用 remove() 方法删除值为name的值(8) __________________________________________________editor.remove("age");editor.apply();name = sp.getString("name", "default");age = sp.getInt("age", 0);break;case R.id.btn_Clear:// editor 调用 clear()方法清空数据(9)___________________________________________________editor.apply();if (name.equals("default") && age == 0) {// 文件组件tvData上显示无数据(10) _____________________________________________}break;}}}
查看答案
搜索结果不匹配?点我反馈