Android——共享参数SharedPreferences

港控/mmm° 2024-04-08 08:51 121阅读 0赞

4数据存储

共享参数SharedPreferences、数据库SQLite、SD卡文件、App的全局内存

4.1共享参数SharedPreferences

SharedPreferences是一个轻量级存储工具,采用的存储结构时Key-Value的键值对方式

SharedPreferences的存储介质是符合XML规范的配置文件。

保存SharedPreferences键值对信息的文件路径时/data/data/应用包名/shared_prefs/文件名.xml

  1. <?xml version='1.0' encoding='utf-8' standalone='yes'?>
  2. <map>
  3. <string name="name"></string>
  4. <int name="age" value="30"/>
  5. <boolean name="married" value="true"/>
  6. <float name="weight" value="100.0"/>
  7. </map>

基于XML格式的特点,SharedPreferences主要适用于如下场合:

  1. 简单且孤立的数据。若是复杂且相互间有关的数据,则要保存在数据库中。
  2. 文本形式的数据。若是二进制数据,则要保存在文件中。
  3. 需要持久化存储的数据。在App退出后再次启动时,之前保存的数据仍然有效。

实际开发中,共享参数经常存储的数据有App的个性化配置信息、用户使用App的行为信息、临时需要保存的片段信息等

SharedPreferences对数据的存储和读取操作类似于Map,也有put函数用于存储数据、get函数用于读取数据。在使用共享参数之前,要先调用getSharedPreferences函数声明文件名与操作模式:

  1. SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);

getSharedPreferences方法的第一个参数是文件名,上面的share表示当前使用的共享参数文件名是share.xml;第二个参数是操作模式,一般都填MODE_PRIVATE,表示私有模式。

共享参数存储数据要借助于Editor类:

  1. SharedPreferences.Editor editor = shared.edit();// 获得编辑器的对象
  2. editor.putString("name","Mr Lee");// 添加一个名叫name的字符串参数
  3. editor.putInt("age",23);// 添加一个名叫age的整形参数
  4. editor.putBoolean("married",true);// 添加一个名叫married的布尔型参数
  5. editor.putFloat("weight",100f);// 添加一个名叫weight的浮点数参数
  6. editor.commit();// 提交编辑器中的修改

共享参数读取数据相对简单,直接使用对象即可完成数据读取方法的调用,注意get方法的第二个参数表示默认值:

  1. String name = shared.getString("name","");// 从共享参数中获得名叫name的字符串
  2. int age = shared.getInt("age",0);// 从共享参数中获得名叫age的整形数
  3. boolean married = getBoolean("married",false);// 从共享参数中获得名叫married的布尔数
  4. float weight = getFloat("weight",0);// 从共享参数中获得名叫weight的浮点数

Write:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:focusable="true"
  5. android:focusableInTouchMode="true"
  6. android:orientation="vertical"
  7. android:padding="10dp" >
  8. <RelativeLayout
  9. android:layout_width="match_parent"
  10. android:layout_height="50dp" >
  11. <TextView
  12. android:id="@+id/tv_name"
  13. android:layout_width="wrap_content"
  14. android:layout_height="match_parent"
  15. android:layout_alignParentLeft="true"
  16. android:gravity="center"
  17. android:text="姓名:"
  18. android:textColor="@color/black"
  19. android:textSize="17sp" />
  20. <EditText
  21. android:id="@+id/et_name"
  22. android:layout_width="match_parent"
  23. android:layout_height="match_parent"
  24. android:layout_marginBottom="5dp"
  25. android:layout_marginTop="5dp"
  26. android:layout_toRightOf="@+id/tv_name"
  27. android:background="@drawable/editext_selector"
  28. android:gravity="left|center"
  29. android:hint="请输入姓名"
  30. android:inputType="text"
  31. android:maxLength="12"
  32. android:textColor="@color/black"
  33. android:textColorHint="@color/grey"
  34. android:textCursorDrawable="@drawable/text_cursor"
  35. android:textSize="17sp" />
  36. </RelativeLayout>
  37. <RelativeLayout
  38. android:layout_width="match_parent"
  39. android:layout_height="50dp" >
  40. <TextView
  41. android:id="@+id/tv_age"
  42. android:layout_width="wrap_content"
  43. android:layout_height="match_parent"
  44. android:layout_alignParentLeft="true"
  45. android:gravity="center"
  46. android:text="年龄:"
  47. android:textColor="@color/black"
  48. android:textSize="17sp" />
  49. <EditText
  50. android:id="@+id/et_age"
  51. android:layout_width="match_parent"
  52. android:layout_height="match_parent"
  53. android:layout_marginBottom="5dp"
  54. android:layout_marginTop="5dp"
  55. android:layout_toRightOf="@+id/tv_age"
  56. android:background="@drawable/editext_selector"
  57. android:gravity="left|center"
  58. android:hint="请输入年龄"
  59. android:inputType="number"
  60. android:maxLength="2"
  61. android:textColor="@color/black"
  62. android:textColorHint="@color/grey"
  63. android:textCursorDrawable="@drawable/text_cursor"
  64. android:textSize="17sp" />
  65. </RelativeLayout>
  66. <RelativeLayout
  67. android:layout_width="match_parent"
  68. android:layout_height="50dp" >
  69. <TextView
  70. android:id="@+id/tv_height"
  71. android:layout_width="wrap_content"
  72. android:layout_height="match_parent"
  73. android:layout_alignParentLeft="true"
  74. android:gravity="center"
  75. android:text="身高:"
  76. android:textColor="@color/black"
  77. android:textSize="17sp" />
  78. <EditText
  79. android:id="@+id/et_height"
  80. android:layout_width="match_parent"
  81. android:layout_height="match_parent"
  82. android:layout_marginBottom="5dp"
  83. android:layout_marginTop="5dp"
  84. android:layout_toRightOf="@+id/tv_height"
  85. android:background="@drawable/editext_selector"
  86. android:gravity="left|center"
  87. android:hint="请输入身高"
  88. android:inputType="number"
  89. android:maxLength="3"
  90. android:textColor="@color/black"
  91. android:textColorHint="@color/grey"
  92. android:textCursorDrawable="@drawable/text_cursor"
  93. android:textSize="17sp" />
  94. </RelativeLayout>
  95. <RelativeLayout
  96. android:layout_width="match_parent"
  97. android:layout_height="50dp" >
  98. <TextView
  99. android:id="@+id/tv_weight"
  100. android:layout_width="wrap_content"
  101. android:layout_height="match_parent"
  102. android:layout_alignParentLeft="true"
  103. android:gravity="center"
  104. android:text="体重:"
  105. android:textColor="@color/black"
  106. android:textSize="17sp" />
  107. <EditText
  108. android:id="@+id/et_weight"
  109. android:layout_width="match_parent"
  110. android:layout_height="match_parent"
  111. android:layout_marginBottom="5dp"
  112. android:layout_marginTop="5dp"
  113. android:layout_toRightOf="@+id/tv_weight"
  114. android:background="@drawable/editext_selector"
  115. android:gravity="left|center"
  116. android:hint="请输入体重"
  117. android:inputType="numberDecimal"
  118. android:maxLength="5"
  119. android:textColor="@color/black"
  120. android:textColorHint="@color/grey"
  121. android:textCursorDrawable="@drawable/text_cursor"
  122. android:textSize="17sp" />
  123. </RelativeLayout>
  124. <RelativeLayout
  125. android:layout_width="match_parent"
  126. android:layout_height="50dp" >
  127. <TextView
  128. android:id="@+id/tv_married"
  129. android:layout_width="wrap_content"
  130. android:layout_height="match_parent"
  131. android:layout_alignParentLeft="true"
  132. android:gravity="center"
  133. android:text="婚否:"
  134. android:textColor="@color/black"
  135. android:textSize="17sp" />
  136. <Spinner
  137. android:id="@+id/sp_married"
  138. android:layout_width="match_parent"
  139. android:layout_height="match_parent"
  140. android:layout_toRightOf="@+id/tv_married"
  141. android:gravity="left|center"
  142. android:spinnerMode="dialog" />
  143. </RelativeLayout>
  144. <Button
  145. android:id="@+id/btn_save"
  146. android:layout_width="match_parent"
  147. android:layout_height="wrap_content"
  148. android:text="保存到共享参数"
  149. android:textColor="@color/black"
  150. android:textSize="20sp" />
  151. </LinearLayout>
  152. public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener {
  153. private SharedPreferences mShared;
  154. private EditText et_name;
  155. private EditText et_age;
  156. private EditText et_height;
  157. private EditText et_weight;
  158. private boolean bMarried = false;
  159. @Override
  160. protected void onCreate(Bundle savedInstanceState) {
  161. super.onCreate(savedInstanceState);
  162. setContentView(R.layout.activity_share_write);
  163. et_name = (EditText) findViewById(R.id.et_name);
  164. et_age = (EditText) findViewById(R.id.et_age);
  165. et_height = (EditText) findViewById(R.id.et_height);
  166. et_weight = (EditText) findViewById(R.id.et_weight);
  167. findViewById(R.id.btn_save).setOnClickListener(this);
  168. ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
  169. R.layout.item_select, typeArray);
  170. typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
  171. Spinner sp_married = (Spinner) findViewById(R.id.sp_married);
  172. sp_married.setPrompt("请选择婚姻状况");
  173. sp_married.setAdapter(typeAdapter);
  174. sp_married.setSelection(0);
  175. sp_married.setOnItemSelectedListener(new TypeSelectedListener());
  176. mShared = getSharedPreferences("share", MODE_PRIVATE);
  177. }
  178. private String[] typeArray = {
  179. "未婚", "已婚"};
  180. class TypeSelectedListener implements AdapterView.OnItemSelectedListener {
  181. public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
  182. bMarried = (arg2==0)?false:true;
  183. }
  184. public void onNothingSelected(AdapterView<?> arg0) {
  185. }
  186. }
  187. @Override
  188. public void onClick(View v) {
  189. if (v.getId() == R.id.btn_save) {
  190. String name = et_name.getText().toString();
  191. String age = et_age.getText().toString();
  192. String height = et_height.getText().toString();
  193. String weight = et_weight.getText().toString();
  194. if (name==null || name.length()<=0) {
  195. showToast("请先填写姓名");
  196. return;
  197. }
  198. if (age==null || age.length()<=0) {
  199. showToast("请先填写年龄");
  200. return;
  201. }
  202. if (height==null || height.length()<=0) {
  203. showToast("请先填写身高");
  204. return;
  205. }
  206. if (weight==null || weight.length()<=0) {
  207. showToast("请先填写体重");
  208. return;
  209. }
  210. SharedPreferences.Editor editor = mShared.edit();
  211. editor.putString("name", name);
  212. editor.putInt("age", Integer.parseInt(age));
  213. editor.putLong("height", Long.parseLong(height));
  214. editor.putFloat("weight", Float.parseFloat(weight));
  215. editor.putBoolean("married", bMarried);
  216. editor.putString("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"));
  217. editor.commit();
  218. showToast("数据已写入共享参数");
  219. }
  220. }
  221. private void showToast(String desc) {
  222. Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
  223. }
  224. }

Read:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:focusable="true"
  5. android:focusableInTouchMode="true"
  6. android:orientation="vertical"
  7. android:padding="10dp" >
  8. <TextView
  9. android:id="@+id/tv_share"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. android:textColor="@color/black"
  13. android:textSize="17sp" />
  14. </LinearLayout>
  15. public class ShareReadActivity extends AppCompatActivity {
  16. private SharedPreferences mShared;
  17. private TextView tv_share;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_share_read);
  22. tv_share = (TextView) findViewById(R.id.tv_share);
  23. readSharedPreferences();
  24. }
  25. private void readSharedPreferences() {
  26. SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);
  27. String desc = "共享参数中保存的信息如下:";
  28. Map<String, Object> mapParam = (Map<String, Object>) mShared.getAll();
  29. for (Map.Entry<String, Object> item_map : mapParam.entrySet()) {
  30. String key = item_map.getKey();
  31. Object value = item_map.getValue();
  32. if (value instanceof String) {
  33. desc = String.format("%s\n %s的取值为%s", desc, key,
  34. mShared.getString(key, ""));
  35. } else if (value instanceof Integer) {
  36. desc = String.format("%s\n %s的取值为%d", desc, key,
  37. mShared.getInt(key, 0));
  38. } else if (value instanceof Float) {
  39. desc = String.format("%s\n %s的取值为%f", desc, key,
  40. mShared.getFloat(key, 0.0f));
  41. } else if (value instanceof Boolean) {
  42. desc = String.format("%s\n %s的取值为%b", desc, key,
  43. mShared.getBoolean(key, false));
  44. } else if (value instanceof Long) {
  45. desc = String.format("%s\n %s的取值为%d", desc, key,
  46. mShared.getLong(key, 0l));
  47. } else {
  48. desc = String.format("%s\n参数%s的取值为未知类型", desc, key);
  49. }
  50. }
  51. if (mapParam==null || mapParam.size()<=0) {
  52. desc = "共享参数中保存的信息为空";
  53. }
  54. tv_share.setText(desc);
  55. }
  56. }

发表评论

表情:
评论列表 (有 0 条评论,121人围观)

还没有评论,来说两句吧...

相关阅读

    相关 七、androidSharedPreferences

    很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用