Android之SharedPreferences
来源:互联网 发布:舆情分析研判数据 编辑:程序博客网 时间:2024/05/19 01:30
SharedPreferences是Android中存储一些轻量级(只能存储key-value对)数据的一种方式,实际上SharedPreferences会把数据保存在xml文件中,可以在/data/data/appPackageName/下查看对应的xml文件。
获取方式
Context对象的getSharedPreferences()和Activity对象的getPreferences()方法。
区别:
getSharedPreferences()获得的SharedPreferences允许该应用程序下的其他组件使用,而getPreferences()获得的SharedPreferences只能在该Activity中使用。
获取和保存数据
//MainActivity.java主要代码: @Override protected void onStart() { super.onStart(); //获取数据 SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE);//person是文件名,对应到person.xml EditText nameEditText = (EditText) findViewById(R.id.name); String name = sharedPreferences.getString(R.id.name+"", ""); nameEditText.setText(name); EditText ageEditText = (EditText) findViewById(R.id.age); String age = sharedPreferences.getString(R.id.age+"", ""); ageEditText.setText(age); } public void saveSetting(View view) { //保存数据 SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE); Editor edit = sharedPreferences.edit(); EditText nameEditText = (EditText) findViewById(R.id.name); edit.putString(R.id.name+"", nameEditText.getText().toString()); EditText ageEditText = (EditText) findViewById(R.id.age); edit.putString(R.id.age+"", ageEditText.getText().toString()); edit.commit(); }
<!-- fragment_main.xml主要代码 --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/name" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/name"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/age" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/age"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/saveButton" android:text="@string/saveSetting" android:onClick="saveSetting"/>
操作模式
Context.MODE_PRIVATE:私有,覆盖。
Context.MODE_APPEND:私有,追加。
Context.MODE_WORLD_READABLE:公开读(其他应用可读)。
Context.MODE_WORLD_WRITEABLE:公开读写(其他应用可读写)。
0 0
- Android 之 SharedPreferences
- Android 之 SharedPreferences
- Android 存储之SharedPreferences
- Android之路-SharedPreferences
- Android之SharedPreferences
- Android 之 SharedPreferences示例
- Android之SharedPreferences权限
- Android基础之SharedPreferences
- Android 存储之SharedPreferences
- Android入门之SharedPreferences
- Android之SharedPreferences权限
- android之SharedPreferences介绍
- android之SharedPreferences简介
- Android之SharedPreferences详解
- android之SharedPreferences
- Android之SharedPreferences详解
- Android初学者之SharedPreferences
- Android之SharedPreferences权限
- 全加和 UVa10943
- Jenkins/hudson:admin没有Read权限
- Spring MVC入门
- 二、创建一个可复用的单链表
- Java 三大框架集成项目结构
- Android之SharedPreferences
- Asp.Net FileUpload选择图片后预览,并直接上传
- hiwifi插件开发
- shell 中获取文件真实路径(绝对路径)
- 5X5点灯游戏
- Maven编译提示:软件包不存在
- 四种方案解决ScrollView嵌套ListView问题
- scrapy爬虫-------命令解析
- struts详解