当前位置:   article > 正文

安卓xml存储读取和sharedpreferences文件存储读取

安卓xml存储读取和sharedpreferences文件存储读取

起因今天有人问到我 xml文件存储读取和sharedpreferences读写该咋做,能不能帮忙写个案例,这里我简单写出一个案例,一下是全部的代码

一、首先引入

权限

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

二、下面是Activity

  1. import androidx.appcompat.app.AppCompatActivity;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import android.os.Bundle;
  5. import android.text.TextUtils;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.Toast;
  10. import org.w3c.dom.Document;
  11. import org.w3c.dom.Element;
  12. import org.xml.sax.SAXException;
  13. import java.io.File;
  14. import java.io.IOException;
  15. import javax.xml.parsers.DocumentBuilder;
  16. import javax.xml.parsers.DocumentBuilderFactory;
  17. import javax.xml.parsers.ParserConfigurationException;
  18. import javax.xml.transform.Transformer;
  19. import javax.xml.transform.TransformerException;
  20. import javax.xml.transform.TransformerFactory;
  21. import javax.xml.transform.dom.DOMSource;
  22. import javax.xml.transform.stream.StreamResult;
  23. public class MainActivity extends AppCompatActivity {
  24. private EditText ed_name;//名字
  25. private EditText ed_school_degree;//学号
  26. private EditText ed_age;//年龄
  27. private EditText ed_gender;//性别
  28. private EditText ed_face;//政治面貌
  29. private EditText ed_address;//家庭住址
  30. private Button btn_save_xml;//保存到xml
  31. private Button btn_read_xml;//从xml读取
  32. private Button btn_save_sharedpreferences;//保存到SharedPreferences
  33. private Button btn_read_sharedpreferences;//从SharedPreferences读取
  34. @Override
  35. protected void onCreate(Bundle savedInstanceState) {
  36. super.onCreate(savedInstanceState);
  37. setContentView(R.layout.activity_main);
  38. ed_name = findViewById(R.id.ed_name);
  39. ed_school_degree = findViewById(R.id.ed_school_degree);
  40. ed_age = findViewById(R.id.ed_age);
  41. ed_gender = findViewById(R.id.ed_gender);
  42. ed_face = findViewById(R.id.ed_face);
  43. ed_address = findViewById(R.id.ed_address);
  44. btn_save_xml = findViewById(R.id.btn_save_xml);
  45. btn_read_xml = findViewById(R.id.btn_read_xml);
  46. // xml文件存储读取
  47. btn_save_xml.setOnClickListener(new View.OnClickListener() {
  48. @Override
  49. public void onClick(View v) {
  50. String name = ed_name.getText().toString();
  51. String school_degree = ed_school_degree.getText().toString();
  52. String age = ed_age.getText().toString();
  53. String gender = ed_gender.getText().toString();
  54. String face = ed_face.getText().toString();
  55. String address = ed_address.getText().toString();
  56. if (TextUtils.isEmpty(name)) {
  57. showToast("请输入姓名");
  58. return;
  59. }
  60. if (TextUtils.isEmpty(school_degree)) {
  61. showToast("请输入学号");
  62. return;
  63. }
  64. if (TextUtils.isEmpty(age)) {
  65. showToast("请输入年龄");
  66. return;
  67. }
  68. if (TextUtils.isEmpty(gender)) {
  69. showToast("请输入性别");
  70. return;
  71. }
  72. if (TextUtils.isEmpty(face)) {
  73. showToast("请输入政治面貌");
  74. return;
  75. }
  76. if (TextUtils.isEmpty(address)) {
  77. showToast("请输入家庭住址");
  78. return;
  79. }
  80. // 创建一个 DocumentBuilder 对象
  81. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  82. DocumentBuilder builder;
  83. try {
  84. builder = factory.newDocumentBuilder();
  85. Document doc = builder.newDocument();
  86. // 创建根元素
  87. Element rootElement = doc.createElement("student");
  88. doc.appendChild(rootElement);
  89. // 创建子元素并设置文本内容
  90. Element nameElement = doc.createElement("name");
  91. nameElement.appendChild(doc.createTextNode(name));
  92. rootElement.appendChild(nameElement);
  93. Element schoolDegreeElement = doc.createElement("school_degree");
  94. schoolDegreeElement.appendChild(doc.createTextNode(school_degree));
  95. rootElement.appendChild(schoolDegreeElement);
  96. Element ageElement = doc.createElement("age");
  97. ageElement.appendChild(doc.createTextNode(age));
  98. rootElement.appendChild(ageElement);
  99. Element genderElement = doc.createElement("gender");
  100. genderElement.appendChild(doc.createTextNode(gender));
  101. rootElement.appendChild(genderElement);
  102. Element faceElement = doc.createElement("face");
  103. faceElement.appendChild(doc.createTextNode(face));
  104. rootElement.appendChild(faceElement);
  105. Element addressElement = doc.createElement("address");
  106. addressElement.appendChild(doc.createTextNode(address));
  107. rootElement.appendChild(addressElement);
  108. // 将文档写入 XML 文件
  109. TransformerFactory transformerFactory = TransformerFactory.newInstance();
  110. Transformer transformer = transformerFactory.newTransformer();
  111. DOMSource source = new DOMSource(doc);
  112. StreamResult result = new StreamResult(new File(getFilesDir(), "student_info.xml"));
  113. transformer.transform(source, result);
  114. showToast("学生信息已保存到 XML 文件");
  115. } catch (ParserConfigurationException | TransformerException e) {
  116. e.printStackTrace();
  117. showToast("保存失败:" + e.getMessage());
  118. }
  119. }
  120. });
  121. btn_read_xml.setOnClickListener(new View.OnClickListener() {
  122. @Override
  123. public void onClick(View v) {
  124. try {
  125. // 创建一个 DocumentBuilder 对象
  126. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  127. DocumentBuilder builder = factory.newDocumentBuilder();
  128. // 从文件中读取 XML 数据
  129. File xmlFile = new File(getFilesDir(), "student_info.xml");
  130. Document doc = builder.parse(xmlFile);
  131. // 获取根元素
  132. Element rootElement = doc.getDocumentElement();
  133. // 获取子元素并读取其文本内容
  134. String name = rootElement.getElementsByTagName("name").item(0).getTextContent();
  135. String school_degree = rootElement.getElementsByTagName("school_degree").item(0).getTextContent();
  136. String age = rootElement.getElementsByTagName("age").item(0).getTextContent();
  137. String gender = rootElement.getElementsByTagName("gender").item(0).getTextContent();
  138. String face = rootElement.getElementsByTagName("face").item(0).getTextContent();
  139. String address = rootElement.getElementsByTagName("address").item(0).getTextContent();
  140. // 显示读取的数据,您可以根据需要修改此部分
  141. showToast("姓名: " + name + "\n" +
  142. "学号: " + school_degree + "\n" +
  143. "年龄: " + age + "\n" +
  144. "性别: " + gender + "\n" +
  145. "政治面貌: " + face + "\n" +
  146. "家庭住址: " + address);
  147. } catch (ParserConfigurationException | SAXException | IOException e) {
  148. e.printStackTrace();
  149. showToast("读取失败:" + e.getMessage());
  150. }
  151. }
  152. });
  153. btn_save_sharedpreferences = findViewById(R.id.btn_save_sharedpreferences);
  154. btn_read_sharedpreferences = findViewById(R.id.btn_read_sharedpreferences);
  155. // sharedpreferences文件存储读取
  156. btn_save_sharedpreferences.setOnClickListener(new View.OnClickListener() {
  157. @Override
  158. public void onClick(View v) {
  159. String name = ed_name.getText().toString();
  160. String school_degree = ed_school_degree.getText().toString();
  161. String age = ed_age.getText().toString();
  162. String gender = ed_gender.getText().toString();
  163. String face = ed_face.getText().toString();
  164. String address = ed_address.getText().toString();
  165. if (TextUtils.isEmpty(name)){
  166. showToast("请输入姓名");
  167. return;
  168. }
  169. if (TextUtils.isEmpty(school_degree)){
  170. showToast("请输入学号");
  171. return;
  172. }
  173. if (TextUtils.isEmpty(age)){
  174. showToast("请输入年龄");
  175. return;
  176. }if (TextUtils.isEmpty(gender)){
  177. showToast("请输入性别");
  178. return;
  179. }if (TextUtils.isEmpty(face)){
  180. showToast("请输入政治面貌");
  181. return;
  182. }if (TextUtils.isEmpty(address)){
  183. showToast("请输入家庭住址");
  184. return;
  185. }
  186. // 使用 SharedPreferences 保存数据
  187. SharedPreferences sharedPreferences = getSharedPreferences("student_info", Context.MODE_PRIVATE);
  188. SharedPreferences.Editor editor = sharedPreferences.edit();
  189. editor.putString("name", name);
  190. editor.putString("school_degree", school_degree);
  191. editor.putString("age", age);
  192. editor.putString("gender", gender);
  193. editor.putString("face", face);
  194. editor.putString("address", address);
  195. editor.apply();
  196. showToast("学生信息已保存到 SharedPreferences");
  197. }
  198. });
  199. btn_read_sharedpreferences.setOnClickListener(new View.OnClickListener() {
  200. @Override
  201. public void onClick(View v) {
  202. // 从 SharedPreferences 中读取学生信息
  203. SharedPreferences sharedPreferences = getSharedPreferences("student_info", Context.MODE_PRIVATE);
  204. String name = sharedPreferences.getString("name", "");
  205. String school_degree = sharedPreferences.getString("school_degree", "");
  206. String age = sharedPreferences.getString("age", "");
  207. String gender = sharedPreferences.getString("gender", "");
  208. String face = sharedPreferences.getString("face", "");
  209. String address = sharedPreferences.getString("address", "");
  210. // 显示读取的数据,您可以根据需要修改此部分
  211. showToast("姓名: " + name + "\n" +
  212. "学号: " + school_degree + "\n" +
  213. "年龄: " + age + "\n" +
  214. "性别: " + gender + "\n" +
  215. "政治面貌: " + face + "\n" +
  216. "家庭住址: " + address);
  217. }
  218. });
  219. }
  220. private void showToast(String msg){
  221. Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
  222. }
  223. }

最后是activity_main.xml 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:orientation="vertical"
  7. android:layout_height="match_parent"
  8. tools:context=".MainActivity">
  9. <LinearLayout
  10. android:layout_width="match_parent"
  11. android:orientation="horizontal"
  12. android:layout_height="60dp">
  13. <TextView
  14. android:layout_width="0dp"
  15. android:text="姓名:"
  16. android:gravity="center"
  17. android:layout_weight="1"
  18. android:layout_height="match_parent"/>
  19. <EditText
  20. android:id="@+id/ed_name"
  21. android:layout_width="0dp"
  22. android:layout_height="match_parent"
  23. android:hint="请输入名字"
  24. android:maxLines="1"
  25. android:lines="1"
  26. android:layout_weight="4"/>
  27. </LinearLayout>
  28. <LinearLayout
  29. android:layout_width="match_parent"
  30. android:orientation="horizontal"
  31. android:layout_marginTop="10dp"
  32. android:layout_height="60dp">
  33. <TextView
  34. android:layout_width="0dp"
  35. android:text="姓名:"
  36. android:gravity="center"
  37. android:layout_weight="1"
  38. android:layout_height="match_parent"/>
  39. <EditText
  40. android:id="@+id/ed_school_degree"
  41. android:layout_width="0dp"
  42. android:layout_height="match_parent"
  43. android:hint="请输入学号"
  44. android:maxLines="1"
  45. android:lines="1"
  46. android:layout_weight="4"/>
  47. </LinearLayout>
  48. <LinearLayout
  49. android:layout_width="match_parent"
  50. android:orientation="horizontal"
  51. android:layout_marginTop="10dp"
  52. android:layout_height="60dp">
  53. <TextView
  54. android:layout_width="0dp"
  55. android:text="年龄:"
  56. android:gravity="center"
  57. android:layout_weight="1"
  58. android:layout_height="match_parent"/>
  59. <EditText
  60. android:id="@+id/ed_age"
  61. android:layout_width="0dp"
  62. android:layout_height="match_parent"
  63. android:hint="请输入年龄"
  64. android:maxLines="1"
  65. android:inputType="number"
  66. android:lines="1"
  67. android:layout_weight="4"/>
  68. </LinearLayout>
  69. <LinearLayout
  70. android:layout_width="match_parent"
  71. android:orientation="horizontal"
  72. android:layout_marginTop="10dp"
  73. android:layout_height="60dp">
  74. <TextView
  75. android:layout_width="0dp"
  76. android:text="性别:"
  77. android:gravity="center"
  78. android:layout_weight="1"
  79. android:layout_height="match_parent"/>
  80. <EditText
  81. android:id="@+id/ed_gender"
  82. android:layout_width="0dp"
  83. android:layout_height="match_parent"
  84. android:hint="请输入性别"
  85. android:maxLines="1"
  86. android:lines="1"
  87. android:layout_weight="4"/>
  88. </LinearLayout>
  89. <LinearLayout
  90. android:layout_width="match_parent"
  91. android:orientation="horizontal"
  92. android:layout_marginTop="10dp"
  93. android:layout_height="60dp">
  94. <TextView
  95. android:layout_width="0dp"
  96. android:text="政治面貌:"
  97. android:gravity="center"
  98. android:layout_weight="1"
  99. android:layout_height="match_parent"/>
  100. <EditText
  101. android:id="@+id/ed_face"
  102. android:layout_width="0dp"
  103. android:layout_height="match_parent"
  104. android:hint="请输入政治面貌"
  105. android:maxLines="1"
  106. android:lines="1"
  107. android:layout_weight="4"/>
  108. </LinearLayout>
  109. <LinearLayout
  110. android:layout_width="match_parent"
  111. android:orientation="horizontal"
  112. android:layout_marginTop="10dp"
  113. android:layout_height="60dp">
  114. <TextView
  115. android:layout_width="0dp"
  116. android:text="家庭住址:"
  117. android:gravity="center"
  118. android:layout_weight="1"
  119. android:layout_height="match_parent"/>
  120. <EditText
  121. android:id="@+id/ed_address"
  122. android:layout_width="0dp"
  123. android:layout_height="match_parent"
  124. android:hint="请输入家庭住址"
  125. android:maxLines="1"
  126. android:lines="1"
  127. android:layout_weight="4"/>
  128. </LinearLayout>
  129. <LinearLayout
  130. android:layout_width="match_parent"
  131. android:orientation="vertical"
  132. android:layout_marginLeft="16dp"
  133. android:layout_marginTop="16dp"
  134. android:layout_marginRight="16dp"
  135. android:layout_height="wrap_content">
  136. <Button
  137. android:id="@+id/btn_save_xml"
  138. android:layout_width="match_parent"
  139. android:layout_height="wrap_content"
  140. android:text="保存到xml"/>
  141. <Button
  142. android:id="@+id/btn_read_xml"
  143. android:layout_width="match_parent"
  144. android:layout_height="wrap_content"
  145. android:layout_marginTop="10dp"
  146. android:text="从xml读取"/>
  147. <Button
  148. android:id="@+id/btn_save_sharedpreferences"
  149. android:layout_width="match_parent"
  150. android:layout_height="wrap_content"
  151. android:layout_marginTop="10dp"
  152. android:text="保存到SharedPreferences"/>
  153. <Button
  154. android:id="@+id/btn_read_sharedpreferences"
  155. android:layout_width="match_parent"
  156. android:layout_height="wrap_content"
  157. android:layout_marginTop="10dp"
  158. android:text="从SharedPreferences读取"/>
  159. </LinearLayout>
  160. </LinearLayout>

效果图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/469965
推荐阅读
相关标签
  

闽ICP备14008679号