Android 数据持久化

一、数据存储

1. 数据存储方式

在这里插入图片描述

二. 文件存储

  • 该存储方式是一种较常见的方法,在Android中读取/写入文件的方法,与Java中实现I/O程序是完全一样的,提供了openFileInput()方法和openFileOutput()方法来读取设备上的文件。
  • 可以存储大数据,如文本、图片、音频
  • 通过java 的I/O流读取磁盘上的文件
    在这里插入图片描述
    在这里插入图片描述

1. 文件存储方式分类

(1). 内部存储

1. 内部存储文件路径

在这里插入图片描述

2. 特点

在这里插入图片描述

3. 过程

在这里插入图片描述

4. 实例:实现备忘录

MainActivity

package com.mingrisoft;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends Activity {

    byte[] buffer = null;  //定义保存数据的数组

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       final EditText etext = (EditText) findViewById(R.id.editText);     //获取用于填写记事本信息的编辑框组件
       ImageButton btn_save = (ImageButton) findViewById(R.id.btn_save);        //获取保存按钮
       ImageButton btn_cancel = (ImageButton) findViewById(R.id.btn_cancel);   //获取取消按钮

        btn_save.setOnClickListener(new View.OnClickListener() {  //实现内部存储填写的文本信息
            @Override
            public void onClick(View v) {
                FileOutputStream fos = null;                         //定义文件输出流
               String text = etext.getText().toString();             //获取文本信息
                try {
                    fos = openFileOutput("memo", MODE_PRIVATE);    //获得文件输出流,,并指定文件保存的位置
                    fos.write(text.getBytes());                      //保存文本信息
                    fos.flush();                                     //清除缓存
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {                              //输出流不为空时
                        try {
                            fos.close();                             //关闭文件输出流
                            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        //实现第二次打开应用时显示上一次所保存的文本信息
        FileInputStream fis = null;                  //声明文件输入流/定义文件输入流
        try {
            fis = openFileInput("memo");             //获得文件输入流
            buffer = new byte[fis.available()];     //保存数据的数组

            fis.read(buffer);                        //从输入流中读取数据
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {                        //输入流不为空时
                try {
                    fis.close();                      //关闭输入流
                    String data = new String(buffer); // 获得数组中保存的数据
                    etext.setText(data);               //将读取的数据保存到编辑框中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        btn_cancel.setOnClickListener(new View.OnClickListener() {  //实现单击取消按钮,退出应用
            @Override
            public void onClick(View v) {
                finish(); //退出应用
            }
        });


    }
}

Layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    tools:context="com.mingrisoft.MainActivity">
    <!--备忘录信息-->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/marginleft"
        android:layout_marginRight="@dimen/marginright"
        android:layout_marginTop="@dimen/margintop"
        android:background="@null"
        android:gravity="top" />
    <!--保存按钮-->
    <ImageButton
        android:id="@+id/btn_save"
        android:layout_width="@dimen/btn_width"
        android:layout_height="@dimen/btn_height"
        android:layout_alignParentRight="true"
        android:src="@drawable/btn1" />
    <!--取消按钮-->
    <ImageButton
        android:id="@+id/btn_cancel"
        android:layout_width="@dimen/btn_width"
        android:layout_height="@dimen/btn_height"
        android:layout_toLeftOf="@+id/btn_save"
        android:src="@drawable/btn2" />
</RelativeLayout>

(2). 外部存储

1. 读写外部存储空间上文件的步骤

在这里插入图片描述

2. 实例:实现备忘录

MainActivity

package com.mingrisoft;

import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends Activity {
    byte[] buffer = null;   //定义保存数据的数组
    private File file;      //定义存储路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText etext = (EditText) findViewById(R.id.editText);      //获取用于填写记事本信息的编辑框组件
        ImageButton btn_save = (ImageButton) findViewById(R.id.save);        //获取保存按钮
        ImageButton btn_abolish = (ImageButton) findViewById(R.id.abolish);  //获取取消按钮
        file = new File(Environment.getExternalStorageDirectory(), "Text.text");  //设置存储sd卡根目录

        btn_save.setOnClickListener(new View.OnClickListener() {  //实现外部存储填写的文本信息
            @Override
            public void onClick(View v) {
                FileOutputStream fos = null;              //定义文件输出流
                String text = etext.getText().toString();        //获取文本信息
                try {
                    fos = new FileOutputStream(file);     //获得文件输出流,并指定文件保存的位置
                    fos.write(text.getBytes());           //保存文本信息
                    fos.flush();                           //清除缓存
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();                    //关闭文件输出流
                            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        //实现第二次打开应用时显示上一次所保存的文本信息
        FileInputStream fis = null;                         //定义文件输入流
        try {
            fis = new FileInputStream(file);                 //获得文件输入流
            buffer = new byte[fis.available()];            //保存数据的数组
            fis.read(buffer);                               //从输入流中读取数据
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();                                      //关闭输入流
                    String data = new String(buffer);                // 获得数组中保存的数据
                    etext.setText(data);                              //保存到编辑框中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        btn_abolish.setOnClickListener(new View.OnClickListener() {  //实现单击取消按钮,退出应用
            @Override
            public void onClick(View v) {
                finish();                                      //退出应用
            }
        });


    }
}

2. XML解析

3. JSON解析

三. SharedPreferences

它是Android提供的,用来以最简单的方式对数据进行永久保存的方法

  • 用来存储一些简单的配置信息的一种机制,采用了XML格式将数据存储到设备中
  • 可以存储应用程序的各种配置信息,如用户名和密码、自定义参数
  • 通过key、value的形式存储数据在xml文件中
  • value值只能是:float、int、boolean、string、stringset

1. SharedPreferences存储的文件格式及路径

在这里插入图片描述

2. 使用SharedPreferences存储数据的步骤

在这里插入图片描述

3. 使用SharedPreferences读取数据的步骤

在这里插入图片描述

4. 举例

在这里插入图片描述
MainActivity

package com.pudding.qqlogin;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity {
    private String adminname = "pudding", adminpassword = "123";    //定义后台用户名与密码
    private String username, password;               //输入的用户名和密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText usernameET = (EditText) findViewById(R.id.username);     //获取用户名编辑框
        final EditText passwordET = (EditText) findViewById(R.id.password);      //获取密码编辑框
        ImageButton login = (ImageButton) findViewById(R.id.login);               //获取登录按钮

        // 获得SharedPreferences对象,并创建文件名称为"data"
        final SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sp.edit();    // 获得Editor对象,用于存储用户名与密码信息

        //判断SharedPreferences文件中,用户名、密码是否存在
        //getString两个参数:一个是key,一个是缺省值,即如果sp中不存在该key,返回缺省值
        if (sp.getString("username", null) != null && sp.getString("password", null) != null) {
            //存在就判断用户名、密码与后台是否相同,相同直接登录
            if (sp.getString("username", username).equals(adminname) && sp.getString("password", password).equals(adminpassword)) {
                Intent intent = new Intent(MainActivity.this, MessageActivity.class);  //通过Intent跳转登录后界面
                startActivity(intent);                                                 //启动跳转界面
            }
        } else {
            //实现SharedPreferences文件不存在时,手动登录并存储用户名与密码
            login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    username = usernameET.getText().toString();            //获得输入的用户名
                    password = passwordET.getText().toString();            //获得输入的密码
                    //如果输入用户名、密码与后台相同时,登录并存储
                    if (username.equals(adminname) && password.equals(adminpassword)) { //判断输入的用户名密码是否正确
                        Toast.makeText(MainActivity.this, "用户名、密码正确", Toast.LENGTH_SHORT).show();
                        Intent  intent = new Intent(MainActivity.this, MessageActivity.class);  //通过Intent跳转登录后界面
                        startActivity(intent);                              //启动跳转界面
                        editor.putString("username", username);           //存储用户名
                        editor.putString("password", password);           //存储密码
                        editor.commit();                                    //提交信息
                        Toast.makeText(MainActivity.this, "已保存用户名密码", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(MainActivity.this, "用户名或密码错误", 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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:orientation="vertical"
    tools:context="com.pudding.qqlogin.MainActivity">
    <!--帐号-->
    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_top_username"
        android:hint="@string/username_hint" />
    <!--密码-->
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_top_password"
        android:hint="@string/password_hint"
        android:inputType="textPassword" />
    <!--登录按钮-->
    <ImageButton
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/login" />

</LinearLayout>

在这里插入图片描述

四、SQLite数据库

  • 是Android自带的一个轻量级的数据库,支持基本的SQL语法,利用很少的内存,就有很好的性能,一般使用它作为复杂数据的存储引擎,可以存储用户信息

1. SQLite数据库简介

(1). 特点

  • 占用资源少
  • 运行效率高
  • 安全可靠
  • 可移植性强

(2). 使用SQLite数据库的方式

  • 使用命令行shell命令(SQLite3工具)
  • 使用java代码操作SQLite

2. 数据库的创建

在这里插入图片描述

3. 数据库的使用

五. ContentProvider(实现数据共享)

见Android的四大组件

  • 两个重要知识点:数据模型、URI

1. 数据模型

  • Content Provider使用基于数据模型的简单表格来提供其中的数据

2. URI

(1). URL(统一资源定位符)

在这里插入图片描述

(2). URI(统一资源标识符)

在这里插入图片描述

3. 创建和使用Content Provider的步骤

在这里插入图片描述

六. 网络存储

  • 需要与Andriod网络数据包打交道,将数据存储到服务器上,通过网络提供的存储空间来存储/获取数据信息
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值