第一行代第六章——详解持久化技术

news/2024/7/24 7:54:17

知识点目录

  • 6.1 持久化技术简介
  • 6.2文件存储
    • 6.2.1将数据存储到文件中
    • 6.2.2 从文件中读取数据
  • 6.3 SharedPreferences存储
    • 6.3.1 将数据存储到SharedPreferences中
  • 6.4 SQLite数据库存储
    • 6.4.1 创建数据库

6.1 持久化技术简介

Android主要提供了3种方式用于实现数据持久化功能:
文件存储
SharedPreferences存储
数据库存储
当然也可以存储到手机SD卡中,但使用上面的三种来保存数据会相对简单一些,也比存储在SD卡中更加安全。

6.2文件存储

文件存储是Android中最基本的一种数据存储方式,有如下特点:
不会对存储的内容进行任何格式化处理,所有数据都是原封不动地保存到文件中
适合存储一些简单的文本数据或二进制数据
如果来保存一些较为复杂的文本数据,就需要定义一套自己的格式规范

6.2.1将数据存储到文件中

Context类中提供了一个openFileOutput()方法,可以用于将数据存储到指定的文件中。该方法接收两个参数:

参数一:文件名。文件不可包含路径,因为所有的文件都是默认存储到/data/data/包名/files/目录下。
参数二:文件的操作模式。有MODE_PRIVATEMODE_APPEND两种

MODE_PRIVATE
默认的操作模式,表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容。
MODE_APPEND
如果文件已经存在,则直接在文件中追加内容,不存在就创建新的文件。

6.2.2 从文件中读取数据

Context类中提供了一个openFileInput()方法,用于从文件中读取数据。该方法只接收一个参数,即要读取的文件名。

例子:从写入读去文件

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "file";
    private EditText editText;
    private TextView textView;
    private Button write;
    private Button read;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        write = findViewById(R.id.write);
        read = findViewById(R.id.read);
        write.setOnClickListener(this);
        read.setOnClickListener(this);
    }

    public void onSaveFile() {
        try {
            FileOutputStream fileOutputStream = this.openFileOutput("data.txt",Context.MODE_PRIVATE);
            String string = editText.getText().toString();
            fileOutputStream.write(string.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void onShowFile() {
        try {
            FileInputStream fileInputStream = this.openFileInput("data.txt");
            byte[] bytes =new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            String string = new String(bytes);
            textView.setText(string);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.read:
                onShowFile();
                break;
            case R.id.write:
                onSaveFile();
                break;
        }
    }

xml

<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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/editText"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:autofillHints="请输入:">
    </EditText>
    <Button
        android:id="@+id/write"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write"
        android:textAllCaps="true">
    </Button>
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </TextView>
    <Button
        android:id="@+id/read"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="read"
        android:textAllCaps="true">
    </Button>
</LinearLayout>

在这里插入图片描述

6.3 SharedPreferences存储

SharedPreferences是使用键值对的方式来存储数据的。

6.3.1 将数据存储到SharedPreferences中

要使用SharedPreferences来存储数据,首先需要获取到SharedPreferences对象。Android中主要提供了3种方法用于得到SharedPreferences对象。

1.Context类中的getSharedPreferences()方法
该方法接收两个参数:
参数一:SharedPreferences文件名称,如果文件名不存在就会创建一个。
SharedPreferences文件都是存放在/data/data/包名/shared_prefs/目录下。
参数二:指定操作模式。
目前只有MODE_PRIVATE这一种模式可选,也是默认的操作模式,和直接传入0的效果相同。

2. Activity类中的getPreferences()方法

这个方法跟Context类中的getSharedPreferences()方法很相似,但只接收一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为SharedPreferences的文件名

3. PreferenceManager类中的getDefaultSharedPreferences()方法

该方法是一个静态方法,它接收一个Context参数,并 自动使用当前应用程序的包名作为前缀来命名SharedPreferences文件

例如:
三种方式进行写入:

//1.context 名字自定
 @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = this.getApplicationContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
  editor.putInt("num",123456789);
  editor.apply();

//2 使用Activity 自带
SharedPreferences.Editor editor1 = this.getPreferences(Context.MODE_PRIVATE).edit();
editor1.putInt("num1",11111);
editor1.apply();

//3. 使用默认的
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).edit().putInt("com",123).apply();

三种方式读出:

//1.contxt
SharedPreferences sharedPreferences = this.getSharedPreferences("data",Context.MODE_PRIVATE);
int num= sharedPreferences.getInt("num",0);
//2 自帶
SharedPreferences sharedPreferences1 = this.getPreferences(Context.MODE_PRIVATE);
int num1 = sharedPreferences1.getInt("num1",0);
//3 默認
int com = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getInt("com",0);

6.4 SQLite数据库存储

Android嵌入了SQLite这一款轻量级的关系型数据库,它具有如下优点:
● 支持标准的SQL语法
● 遵循数据库的ACID事务
● 运算速度非常快
● 占用资源很少,通常只需要几百KB的内存

6.4.1 创建数据库


http://www.niftyadmin.cn/n/1035795.html

相关文章

Vue | 02 入门

什么是Vue.js? Vue&#xff08;读/vjuː/&#xff09;是一个用于构建用户界面的渐进式框架&#xff0c;不同于其它的大框架&#xff0c;Vue是被设计为自底向上适应的&#xff0c;核心库集中在视图层&#xff0c;容易使用以及和其它的库或已经存在的项目集成。另一方面&#x…

第一行代码第七章——探究内容提供器

目录7.1 内容提供器简介7.2 运行权限7.2.1 Android权限机制详解7.2.2 在程序运行时申请权限7.3 访问其他程序中的数据7.3.1 ContentResolver的基本用法7.1 内容提供器简介 内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能。它提供了一套完整的机…

Vue | 03 实例

创建一个Vue实例 每一个Vue应用都需要从使用Vue函数创建一个Vue实例开始&#xff1a; var vm new Vue({//options })虽然和 MVVM pattern 不太相关&#xff0c;Vue的设计部分来自于它的灵感&#xff0c;例如习惯上&#xff0c;我们常常使用vm&#xff08;ViewModel的简写&am…

设计模式 单例

目录概念&#xff1a;常见应用场景优缺点&#xff1a;实现方式&#xff1a;1.饿汉式实现2.懒汉式实现3.双重检测琐式&#xff08;一般不用&#xff09;4.静态内部类的实现&#xff08;懒加载&#xff09;5.枚举实现方式概念&#xff1a; 单例&#xff1a;保证一个类&#xff0…

设计模式 工厂模式

目录工厂模式概念&#xff1a;1.详细分类简单工厂模式工厂方法模式抽象工厂2.简单工厂&#xff1a;工厂模式概念&#xff1a; 实现了创建者和调用者的分离 1.详细分类 简单工厂模式 用来生产同一等级结构中的任意产品&#xff08;对于增加的新产品&#xff0c;需要修改已有…

Vue | 04 模板语法

内容提要&#xff1a; 如何在HTML中插入值&#xff08;包括插入纯文本、生成原生HTML、属性绑定v-bind、JavaScript表达式的使用&#xff09;指令&#xff08;指令的表示方式、参数与修饰符的含义、写法、用法&#xff09;速记&#xff08;速记的意义、使用场景、v-bind和v-on…

通过position属性实现文本在页面中的任意位置

页面文本根据需求需要实现位置的自由设置&#xff0c;需要使用属性position来实现&#xff0c;Demo代码如下所示&#xff1a; <!doctype html> <html> <head> <meta charset"utf-8"> <title>position文本定位</title> <style…

二.自定义View 基础知识attr

知识点整理1.attr1.1 概念2.attr 作用3.attr 使用方式2.attr的简单创建3.format 数据类型具体参考4.attr 的使用前言&#xff1a;自定义view是android自定义控件的核心之一&#xff0c;那么在学习自定义view之前&#xff0c;我们先来了解下自定义view的自定义属性的attr的用法。…