Android数据存储

前言

大部分应用程序都会涉及数据存储,Android也不例外。
Android中的数据存储方式有五种,分别为文件存储、SharedPreferences、SQLite数据库、ContentProvider一句网络存储。

数据存储方式

Android平台提供的五种数据存储方式,各自都有不同的特点,下面就针对这五种方式进行简单的介绍。

● 文件存储: Android提供了openFilenputOlopenFileOutput)方法来读取设备上的文件,其读取方式与Java中IO程序是完全一样的。 ● SharedPreferences: 这是Android提供的用来存储一 些简单的配置信息的一 种机制,它采用了XML格式将数据存储到设备中。通常情况下,我们使用SharedPreferences存储些应用程序的各种配置信息,如用户名、密码等。 ● SQLite数据库: SQLite 是Android自带的一个轻量级的数据库,它运算速度快,占用资源少,还支持基本SQL语法,一般使用它作为复杂数据的存储引擎,可以存储用户信息等。 ● 网络存储:需要与Android网络数据包打交道,将数据存储到服务器上,通过网络提供的存储空间来存储/获取数据信息。

需要注意的是,上述数据存储方式各有优缺点,具体使用哪种方式存储,最好根据开发需求选择存储数据的方式。

文件存储

文件存储是Android中最基本的一种数据存储发方式,其与Java中的文件存储类似,都是通过I/O流的形式把数据直接存储到文件中

● 将数据存入文件中

如果想要将数据存入文件中,有两种存储方式,一种是内部存储,一种是外部存储。其中内部存储是将数据以文件的形式存储到应用中,外部存储是将数据以文件的形式存储到一些外部设备上,如SD卡。

1.内部存储
存储目录:默认位于data/data/包名/files

在这里插入图片描述

Android开发中,内部存储使用Context提供的openFileOutput()方法和openFileInput()方法,这两个方法能够返回进行读写操作的FileOutputStream对象和FileInputStream对象,实例代码如下:

FileOutputStream fos = openFileOuuput(String name,int mode);
FileInputStream fis = openFileInput(String name);
存储数据时,使用FileOutputStream对象将数据存到文件中,实例代码如下:
String FILE_NAME = "data.txt";			//文件名称
String content = "Hello,World";			//保存数据
try{
    FileOutputStream fos = context.openFileOutput(FILE_NAME,MODE_PRIVATE)
    fos.write(content.getBytes()); 				//将输入写入文件中
}catch (Exception e){
   e.printStackTrace();
}finally{
	try{
		if(fos!=null){
			fos.close();		//关闭输出流
		}catch (Exception e){
   e.printStackTrace();
}
		}
	}
}
上述代码中,首先定义了两个String类型的变量fileName和content,这两个变量的值“data.txt”和“HelloWorld”分别表示文件名和要写入文件的数据,接着创建FileOutputStream对象fos,通过该对象的write()方法进行写入。

2.外部存储

外部存储是指将数据以文件的形式存储到一些外部设备 上,例如SD卡或者设备内嵌的存储卡,属于永久性的存储方式(外部存储的文件通常位于mnt/sdcard目录下,不同厂商生产的手机路径可能会不同)。 外部存储的文件可以被其他应用程序所共享,当将外部存储设备连接到计算机时,这些文件可以被浏览、修改和删除,因此这种方式不安全。 由于外部存储设备可能被移除、丢失或者处于其他状态,因此在使用外部设备之前必须使用Environment.getExternalStorageState(方法确认外部设备是否可用,当外部设备可用并且具有读写权限时,那么就可以通过FileInputStream、FileOutputStream对 象来读写外部设备中的文件。 向外部设备(SD卡)中存储数据的示例代码如下:
 String state = Environment.getExternalStorageState();   //获取外部设备状态
        if(state.equals(Environment.MEDIA_MOUNTED)){    //判断外部设备是否可用
            File SDPath = Environment.getExternalStorageDirectory();    //获取SD卡目录
            File file = new File(SDPath,"data.txt");
            String data = "HelloWorld";
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(data.getBytes());
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (fos != null){
                        fos.close();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
上述代码中,Eniroment的gEtExtemalStoragetate(方 法和getExternalStorageDirectory0方法,分别用于判断是否存在SD卡和获取SD卡根目录的路径。由于手机厂商不同,SD卡根目录也可能不同,因此通过getExtemalStorageDirectory(方法获取SD卡目录可以避免把路径写成固定的值而找不到SD卡。

实战演练—保存QQ账号和密码

新建一个名为sharedpreferences的空activity的项目,在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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="50dp"
        app:srcCompat="@drawable/default_icon" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:inputType="text"
            android:hint="请输入用户名"
            android:id="@+id/et_name"
            android:textSize="20dp"
            android:background="@drawable/login_user_name_bg"
            android:layout_marginLeft="50sp"
            android:layout_marginRight="50sp"
            android:paddingLeft="80dp"/>

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/user_name_icon"
            android:layout_marginLeft="50dp"
            android:paddingLeft="20dp"/>

    </FrameLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:inputType="textPassword"
            android:hint="请输入密码"
            android:id="@+id/et_password"
            android:textSize="20dp"
            android:background="@drawable/login_psw_bg"
            android:layout_marginLeft="50sp"
            android:layout_marginRight="50sp"
            android:paddingLeft="80dp"/>

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/psw_icon"
            android:layout_marginLeft="50dp"
            android:paddingLeft="20dp"/>
    </FrameLayout>

    <CheckBox
        android:id="@+id/autoLog"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="自动登录"
        android:textColor="#000"
        android:textSize="20dp"
        android:layout_marginLeft="50sp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"/>

    <Button
        android:id="@+id/btn_log"
        android:text="登录"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textColor="#fff"
        android:background="#F7A42E"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:textSize="30dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="立即注册"
            android:textSize="20dp"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="80dp"
            android:layout_marginRight="60dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="找回密码?"
            android:textSize="20dp"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:layout_marginRight="80dp"/>

    </LinearLayout>

</LinearLayout>

新建一个SPSaveQQ类用于保存账号密码:

package com.example.sharedpreferences;

import android.content.Context;

import java.util.Map;

public class SPSaveQQ {

    //保存  账号和密码
    public static boolean saveAccount(Context context,String account,String password){
        context.getSharedPreferences("data",Context.MODE_PRIVATE).edit()
                .putString("account",account)
                .putString("password",password).apply();
        return true;
    }

    //获取存储的账号和密码
    public static Map<String,String> getAll(Context context){
        return (Map<String,String>) context.getSharedPreferences("data",Context.MODE_PRIVATE)
                .getAll();
    }

    //清除用户信息
    public static void clear(Context context){
        context.getSharedPreferences("data",Context.MODE_PRIVATE).edit()
                .clear().apply();
    }
}

新建一个类FileUtil用于存数据:

package com.example.sharedpreferences;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {
    public static final String FILE_NAME = "data.txt";

    //保存账号和密码到data.txt文件
    public static boolean saveAccount(Context context,String account,String password){

        try(FileOutputStream fos = context.openFileOutput(FILE_NAME,Context.MODE_PRIVATE)) {
            fos.write((account + "," + password).getBytes());

//          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
//          writer.write(account + "," + password);
//          writer.flush();
//          writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return false;
    }

    //从data.txt文件中读取QQ账号和密码
    public static Map<String,String> getAccount(Context context){
        Map<String,String> data = new HashMap<>();
        try{
            FileInputStream fis = context.openFileInput(FILE_NAME);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            String[] infos = new String(buffer).split(",");
            if (infos.length > 0){
                data.put("account",infos[0]);
                data.put("password",infos[1]);
            }
            fis.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return data;
    }

    public static void clear(Context context){
        File file = new File(context.getFilesDir(),FILE_NAME);
        if (file.exists()){
            file.delete();
        }
    }

    //保存到外部存储
    public static Boolean savePublic(Context context,String account,String password){
        //1.检查写SD卡的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions((Activity) context,
                    new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                return false;
            }
        }
        //2.权限被允许的处理
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
            File SDPath = Environment.getExternalStorageDirectory();
            File file = new File(SDPath,FILE_NAME);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write((account + "," + password).getBytes());
                fos.close();
                return true;
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return false;
    }

    //保存到外部存储
    public static Map<String,String> getPublic(Context context){
        Map<String,String> content = new HashMap<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions((Activity)content,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},2);
                return content;
            }
        }
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)){
            File SDPath = Environment.getExternalStorageDirectory();  //获取SD卡路径
            File file = new File(SDPath,FILE_NAME);     //创建文件对象
            try {
                FileInputStream fis = new FileInputStream(file);    //创建文件输入流对象
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));  //创建输入缓冲流的对象
                String data = br.readLine();    //读取数据
                String [] infos = data.split(",");
                if (infos.length > 0){
                    content.put("account",infos[0]);
                    content.put("password",infos[1]);
                }
                br.close();     //关闭字符输入缓冲流
                fis.close();    //挂你输入流
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return content;
    }

    public static void clearPublic(){
        File SDPath = Environment.getExternalStorageDirectory();
        File file = new File(SDPath,FILE_NAME);
        if (file.exists()){
            file.delete();
        }
    }


}

启动该项目,会出现以下界面。

在这里插入图片描述
选中自动登录按钮,账号和密码会保存在"data.txt"文件中,再次启动该项目会自动填入账号密码。

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值