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

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

一、首先引入

权限

XML 复制代码
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

二、下面是Activity

java 复制代码
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;//保存到xml
    private Button btn_read_xml;//从xml读取
    private Button btn_save_sharedpreferences;//保存到SharedPreferences
    private Button btn_read_sharedpreferences;//从SharedPreferences读取

    @Override
    protected 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() {
            @Override
            public 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() {
            @Override
            public 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() {
            @Override
            public 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() {
            @Override
            public 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 复制代码
<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="姓名:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="姓名:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="年龄:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="性别:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="政治面貌:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_height="60dp">

        <TextView
            android:layout_width="0dp"
            android:text="家庭住址:"
            android:gravity="center"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

        <EditText
            android: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>
   <LinearLayout
       android:layout_width="match_parent"
       android:orientation="vertical"
       android:layout_marginLeft="16dp"
       android:layout_marginTop="16dp"
       android:layout_marginRight="16dp"
       android:layout_height="wrap_content">
       <Button
           android:id="@+id/btn_save_xml"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="保存到xml"/>
       <Button
           android:id="@+id/btn_read_xml"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="10dp"
           android:text="从xml读取"/>

       <Button
           android:id="@+id/btn_save_sharedpreferences"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="10dp"
           android:text="保存到SharedPreferences"/>

       <Button
           android:id="@+id/btn_read_sharedpreferences"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="10dp"
           android:text="从SharedPreferences读取"/>
   </LinearLayout>
</LinearLayout>

效果图

相关推荐
吉哥机顶盒刷机10 小时前
好物分享:DNA-Android-4.0.5安卓固件解包、打包工具
android·好物分享
三棱球11 小时前
App逆向学习笔记(三)——Android开发入门课
android·笔记
安卓机器12 小时前
rom定制系列------魅族16x 解锁bl root与Flyme9安卓10线刷固件 传感器修复
android·魅族16x玩机
wellc13 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
untE EADO14 小时前
Tomcat的server.xml配置详解
xml·java·tomcat
CYY9514 小时前
Android 打印 SO 库的异常日志
android
找藉口是失败者的习惯15 小时前
深入理解 Android 无障碍服务
android
summerkissyou198715 小时前
Android-SurfaceView-打开车机SurfaceFlinger和HWC的日志
android
Fate_I_C16 小时前
Android函数式编程代码规范文档
android·代码规范