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

起因今天有人问到我 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;//保存到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 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>

效果图

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来之梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值