起因今天有人问到我 xml文件存储读取和sharedpreferences读写该咋做,能不能帮忙写个案例,这里我简单写出一个案例,一下是全部的代码
一、首先引入
权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
二、下面是Activity
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;import java.io.File;
import java.io.IOException;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;public class MainActivity extends AppCompatActivity {private EditText ed_name;//名字private EditText ed_school_degree;//学号private EditText ed_age;//年龄private EditText ed_gender;//性别private EditText ed_face;//政治面貌private EditText ed_address;//家庭住址private Button btn_save_xml;//保存到xmlprivate Button btn_read_xml;//从xml读取private Button btn_save_sharedpreferences;//保存到SharedPreferencesprivate Button btn_read_sharedpreferences;//从SharedPreferences读取@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ed_name = findViewById(R.id.ed_name);ed_school_degree = findViewById(R.id.ed_school_degree);ed_age = findViewById(R.id.ed_age);ed_gender = findViewById(R.id.ed_gender);ed_face = findViewById(R.id.ed_face);ed_address = findViewById(R.id.ed_address);btn_save_xml = findViewById(R.id.btn_save_xml);btn_read_xml = findViewById(R.id.btn_read_xml);
// xml文件存储读取btn_save_xml.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String name = ed_name.getText().toString();String school_degree = ed_school_degree.getText().toString();String age = ed_age.getText().toString();String gender = ed_gender.getText().toString();String face = ed_face.getText().toString();String address = ed_address.getText().toString();if (TextUtils.isEmpty(name)) {showToast("请输入姓名");return;}if (TextUtils.isEmpty(school_degree)) {showToast("请输入学号");return;}if (TextUtils.isEmpty(age)) {showToast("请输入年龄");return;}if (TextUtils.isEmpty(gender)) {showToast("请输入性别");return;}if (TextUtils.isEmpty(face)) {showToast("请输入政治面貌");return;}if (TextUtils.isEmpty(address)) {showToast("请输入家庭住址");return;}// 创建一个 DocumentBuilder 对象DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder;try {builder = factory.newDocumentBuilder();Document doc = builder.newDocument();// 创建根元素Element rootElement = doc.createElement("student");doc.appendChild(rootElement);// 创建子元素并设置文本内容Element nameElement = doc.createElement("name");nameElement.appendChild(doc.createTextNode(name));rootElement.appendChild(nameElement);Element schoolDegreeElement = doc.createElement("school_degree");schoolDegreeElement.appendChild(doc.createTextNode(school_degree));rootElement.appendChild(schoolDegreeElement);Element ageElement = doc.createElement("age");ageElement.appendChild(doc.createTextNode(age));rootElement.appendChild(ageElement);Element genderElement = doc.createElement("gender");genderElement.appendChild(doc.createTextNode(gender));rootElement.appendChild(genderElement);Element faceElement = doc.createElement("face");faceElement.appendChild(doc.createTextNode(face));rootElement.appendChild(faceElement);Element addressElement = doc.createElement("address");addressElement.appendChild(doc.createTextNode(address));rootElement.appendChild(addressElement);// 将文档写入 XML 文件TransformerFactory transformerFactory = TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();DOMSource source = new DOMSource(doc);StreamResult result = new StreamResult(new File(getFilesDir(), "student_info.xml"));transformer.transform(source, result);showToast("学生信息已保存到 XML 文件");} catch (ParserConfigurationException | TransformerException e) {e.printStackTrace();showToast("保存失败:" + e.getMessage());}}});btn_read_xml.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {// 创建一个 DocumentBuilder 对象DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();// 从文件中读取 XML 数据File xmlFile = new File(getFilesDir(), "student_info.xml");Document doc = builder.parse(xmlFile);// 获取根元素Element rootElement = doc.getDocumentElement();// 获取子元素并读取其文本内容String name = rootElement.getElementsByTagName("name").item(0).getTextContent();String school_degree = rootElement.getElementsByTagName("school_degree").item(0).getTextContent();String age = rootElement.getElementsByTagName("age").item(0).getTextContent();String gender = rootElement.getElementsByTagName("gender").item(0).getTextContent();String face = rootElement.getElementsByTagName("face").item(0).getTextContent();String address = rootElement.getElementsByTagName("address").item(0).getTextContent();// 显示读取的数据,您可以根据需要修改此部分showToast("姓名: " + name + "\n" +"学号: " + school_degree + "\n" +"年龄: " + age + "\n" +"性别: " + gender + "\n" +"政治面貌: " + face + "\n" +"家庭住址: " + address);} catch (ParserConfigurationException | SAXException | IOException e) {e.printStackTrace();showToast("读取失败:" + e.getMessage());}}});btn_save_sharedpreferences = findViewById(R.id.btn_save_sharedpreferences);btn_read_sharedpreferences = findViewById(R.id.btn_read_sharedpreferences);
// sharedpreferences文件存储读取btn_save_sharedpreferences.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String name = ed_name.getText().toString();String school_degree = ed_school_degree.getText().toString();String age = ed_age.getText().toString();String gender = ed_gender.getText().toString();String face = ed_face.getText().toString();String address = ed_address.getText().toString();if (TextUtils.isEmpty(name)){showToast("请输入姓名");return;}if (TextUtils.isEmpty(school_degree)){showToast("请输入学号");return;}if (TextUtils.isEmpty(age)){showToast("请输入年龄");return;}if (TextUtils.isEmpty(gender)){showToast("请输入性别");return;}if (TextUtils.isEmpty(face)){showToast("请输入政治面貌");return;}if (TextUtils.isEmpty(address)){showToast("请输入家庭住址");return;}// 使用 SharedPreferences 保存数据SharedPreferences sharedPreferences = getSharedPreferences("student_info", Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putString("name", name);editor.putString("school_degree", school_degree);editor.putString("age", age);editor.putString("gender", gender);editor.putString("face", face);editor.putString("address", address);editor.apply();showToast("学生信息已保存到 SharedPreferences");}});btn_read_sharedpreferences.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 从 SharedPreferences 中读取学生信息SharedPreferences sharedPreferences = getSharedPreferences("student_info", Context.MODE_PRIVATE);String name = sharedPreferences.getString("name", "");String school_degree = sharedPreferences.getString("school_degree", "");String age = sharedPreferences.getString("age", "");String gender = sharedPreferences.getString("gender", "");String face = sharedPreferences.getString("face", "");String address = sharedPreferences.getString("address", "");// 显示读取的数据,您可以根据需要修改此部分showToast("姓名: " + name + "\n" +"学号: " + school_degree + "\n" +"年龄: " + age + "\n" +"性别: " + gender + "\n" +"政治面貌: " + face + "\n" +"家庭住址: " + address);}});}private void showToast(String msg){Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();}
}
最后是activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:orientation="vertical"android:layout_height="match_parent"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="姓名:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_name"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入名字"android:maxLines="1"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_marginTop="10dp"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="姓名:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_school_degree"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入学号"android:maxLines="1"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_marginTop="10dp"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="年龄:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_age"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入年龄"android:maxLines="1"android:inputType="number"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_marginTop="10dp"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="性别:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_gender"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入性别"android:maxLines="1"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_marginTop="10dp"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="政治面貌:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_face"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入政治面貌"android:maxLines="1"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="horizontal"android:layout_marginTop="10dp"android:layout_height="60dp"><TextViewandroid:layout_width="0dp"android:text="家庭住址:"android:gravity="center"android:layout_weight="1"android:layout_height="match_parent"/><EditTextandroid:id="@+id/ed_address"android:layout_width="0dp"android:layout_height="match_parent"android:hint="请输入家庭住址"android:maxLines="1"android:lines="1"android:layout_weight="4"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:orientation="vertical"android:layout_marginLeft="16dp"android:layout_marginTop="16dp"android:layout_marginRight="16dp"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn_save_xml"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="保存到xml"/><Buttonandroid:id="@+id/btn_read_xml"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="从xml读取"/><Buttonandroid:id="@+id/btn_save_sharedpreferences"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="保存到SharedPreferences"/><Buttonandroid:id="@+id/btn_read_sharedpreferences"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:text="从SharedPreferences读取"/></LinearLayout>
</LinearLayout>
效果图