• Android本地数据存储(SP、SQLite、Room)


    Android本地数据存储常用的有三种方式

    1、SP存储,key-value的方式存储在本地的xml文件中,/data/data/xxx.xx/shared_prefs/xxx.xml
    2、sqlite存储
    3、room存储

    一、SP存储使用

    SP通常用于存储配置信息,如果app风格主题、登录用户名、密码等少量数据,不适于存储大量数据。

    在Activity中通过调用基类方法getSharedPreferences()获取操作实例对象

    该方法需要传入两个参数

    • 参数1,存储数据的xml文件名称
    • 参数2,模式,有3个可选值,默认使用Context.MODE_PRIVATE
    1. MODE_PRIVATE:只有本应用程序才可以对这个文件进行读写
    2. MODE_WORLD_READABLE:其他应用对这个 SharedPreferences 文件只能读不能修改。
    3. MODE_WORLD_WRITEABLE:这个 SharedPreferences 文件能被其他的应用读写。

    使用代码示例

    1、登录成功时,存储账户密码

    // 登录成功记录本次登录信息
    SharedPreferences sp = getSharedPreferences("login_sp_info", Context.MODE_PRIVATE);
    SharedPreferences.Editor edit = sp.edit();
    edit.putString("username",usernameEditText.getText().toString());
    edit.putString("password",passwordEditText.getText().toString());
    edit.apply();//提交数据保存
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、打开app时,获取存储的账户密码,显示到页面上

    //设置上次记录的用户信息
    SharedPreferences sp = getSharedPreferences("login_sp_info", Context.MODE_PRIVATE);
    String username = sp.getString("username","");
    String password = sp.getString("password","");
    companycodeEditText.setText(companycode);
    usernameEditText.setText(username);
    passwordEditText.setText(password);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    二、SQLite存储使用

    • SQLite是一个轻量级数据库,它设计目标是嵌入式的,而且占用资源非常低
    • SQLite没有服务器进程,通过文件保存数据,该文件是跨平台的
    • 支持null,integer,real,text,blob五种数据类型,实际上SQLite也接受varchar,char,decimal等数据类型,只不过在运算中或保存时会转换成对应的5种数据类型,因此,可以将各种类型数据保存到任何字段中

    1、创建数据库

    Android系统推荐使用SQLiteOpenHelper的子类创建数据库,因此需要创建一个类继承自SQLiteOpenHelper,并重写该类的onCreate和onUpgrade方法即可。

    这里使用单例模式创建,在首次调用DBHelper时就会自动执行创建数据库操作

    public class DBHelper extends SQLiteOpenHelper {
    
        private volatile static DBHelper instance;
    
        public static DBHelper getInstance(Context context) {
            if (instance == null) {
                synchronized (DBHelper.class) {
                    if (instance == null) {
                        instance = new DBHelper(context, "mytest.db", null, 1);
                    }
                }
            }
            return instance;
        }
    
        /**
         * 作为SQLiteOpenHelper子类必须有的构造方法
         * @param context 上下文参数
         * @param name 数据库名字
         * @param factory 游标工厂 ,通常是null
         * @param version 数据库的版本
         */
        private DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    
        /**
         * 数据库第一次被创建时调用该方法
         * @param db
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            // 初始化数据库的表结构,执行一条建表的SQL语句
            String sql ="create table persons(_id integer primary key autoincrement, name text, sex text, age integer)";
            db.execSQL(sql);
        }
    
        /**
         * 当数据库的版本号增加调用
         * @param db
         * @param oldVersion
         * @param newVersion
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    2、增删改查操作

    SQLiteOpenHelper提供了直接执行sql语句的方法execSQL(),同时也提供了对应的增删改查四个方法insert、delete、update、query

    1)插入数据

    方法一,执行sql

    public void insert(View view) {
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getWritableDatabase();
        if (!db.isOpen()) {
            return;
        }
        String sql = "insert into persons(name,sex,age) values('张三','男',20)";
        db.execSQL(sql);
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    方法二,执行insert方法

    public void insert2(View view) {
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getWritableDatabase();
        if (!db.isOpen()) {
            return;
        }
    
        ContentValues values = new ContentValues();
        values.put("name", "王五");
        values.put("sex", "女");
        values.put("age", 30);
        // 插入数据
        // insert方法参数1:要插入的表名
        // insert方法参数2:如果发现将要插入的行为空时,会将这个列名的值设为null
        // insert方法参数3:contentValue
        db.insert("persons", null, values);
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    2)删除数据
    public void deleteData(View view) {
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getWritableDatabase();
        if (!db.isOpen()) {
            return;
        }
        String sql = "delete from persons where _id=?";
        db.execSQL(sql, new Object[]{3});
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    3)修改数据
    public void updateData(View view) {
    
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getWritableDatabase();
        if (!db.isOpen()) {
            return;
        }
        String sql = "update persons set name =? where _id=?";
        db.execSQL(sql, new Object[]{"李四", 2});
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    4)查询数据

    方法一,执行sql

    public void query(View view) {
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getReadableDatabase();
        if (!db.isOpen()) {
            return;
        }
        Cursor cursor = db.rawQuery("select * from persons", null);
        while (cursor.moveToNext()) {
            int _id = cursor.getInt(cursor.getColumnIndex("_id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String sex = cursor.getString(cursor.getColumnIndex("sex"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            Log.d("test", "query: _id: " + _id + ", name: " + name + ",sex: " + sex + ",age: " + age);
        }
        cursor.close();
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    方法二,执行query方法

    public void query2(View view) {
        DBHelper instance = DBHelper.getInstance(this);
        SQLiteDatabase db = instance.getReadableDatabase();
        // 参数1:table_name
        // 参数2:columns 要查询出来的列名。相当于 select  *** from table语句中的 ***部分
        // 参数3:selection 查询条件字句,在条件子句允许使用占位符“?”表示条件值
        // 参数4:selectionArgs :对应于 selection参数 占位符的值
        // 参数5:groupby 相当于 select *** from table where && group by ... 语句中 ... 的部分
        // 参数6:having 相当于 select *** from table where && group by ...having %%% 语句中 %%% 的部分
        // 参数7:orderBy :相当于 select  ***from ??  where&& group by ...having %%% order by@@语句中的@@ 部分,如: personid desc(按person 降序)
        Cursor cursor = db.query("persons", null, null, null, null, null, null);
        while (cursor.moveToNext()) { // 游标只要不是在最后一行之后,就一直循环
            int _id = cursor.getInt(0);
            String name = cursor.getString(1);
            String sex = cursor.getString(2);
            int age = cursor.getInt(3);
            Log.d("test", "query: _id: " + _id + ", name: " + name + ",sex: " + sex + ",age: " + age);
        }
        cursor.close();
        db.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    三、Room存储使用

    Room在SQLite基础上做了ORM封装,使用起来类似JPA,不需要写太多的sql。

    准备,导入依赖

    //room
    def room_version="2.4.2"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
    //implementation "androidx.room:room-rxjava2:$room_version"
    //implementation "androidx.room:room-rxjava3:$room_version"
    //implementation "androidx.room:room-guava:$room_version"
    //testImplementation "androidx.room:room-testing:$room_version"
    //implementation "androidx.room:room-paging:2.5.0-alpha01"
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    关键注解说明

    1、@Database:Room数据库对象。该类需要继承自RoomDatabase,通过Room.databaseBuilder()结合单例设计模式,完成数据库的创建工作。我们创建的Dao对象,在这里以抽象方法的形式返回,只需一行代码即可。

    • entities:指定该数据库有哪些表
    • version:指定数据库版本号,后续数据库的升级正是依据版本号来判断的

    2、@Entity:该类与Room中表关联起来。tableName属性可以为该表设置名字,如果不设置,则表名与类名相同。

    3、@PrimaryKey:用于指定该字段作为表的主键。

    4、@ColumnInfo:设置该字段存储在数据库表中的名字并指定字段的类型;默认字段名和属性名一样

    5、@Ignore:忽略该字段

    使用代码示例

    1、创建实体类,对应数据库中一张表,使用注解@Entity

    @Entity
    public class Person {
    
        // 主键,自增长
        @PrimaryKey(autoGenerate = true)
        private int id;
        private String name;
        private String sex;
        private int age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2、创建Dao类,用于操作数据,使用注解@Dao

    @Dao
    public interface PersonDao {
        // 插入
        @Insert
        void insertPersons(Person... persons);
        // 修改
        @Update
        void updatePersons(Person... persons);
        // 删除所有
        @Query("delete from Person")
        void deleteAllPersons();
        // 删除指定实体
        @Delete
        void deletePersons(Person... persons);
        // 根据id删除
        @Query("delete from Person where id in (:ids)")
        void deleteByIds(int ...ids);
        // 根据id查询
        @Query("select * from Person where id in (:ids)")
        List<Person> selectByIds(int ...ids);
        // 查询所有
        @Query("select * from Person order by id desc")
        List<Person> selectAllPersons();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3、创建数据库对象Database,继承RoomDatabase,使用单例模式返回实例

    @Database(entities = {Person.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
        public abstract PersonDao personDao();
    
        private volatile static AppDatabase instance;
    
        public static AppDatabase getInstance(Context context){
            if (instance == null) {
                synchronized (DBHelper.class) {
                    if (instance == null) {
                        instance = Room.databaseBuilder(context, AppDatabase.class, "person.db").build();
                    }
                }
            }
            return instance;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    4、在Activity中使用

    Room数据操作必须在异步线程中执行,所以在Activity中使用线程池执行

    ExecutorService pool = Executors.newCachedThreadPool();
    
    // 插入数据
    public void insertRoom(View view) {
        AppDatabase db = AppDatabase.getInstance(getApplicationContext());
    
        pool.execute(() -> {
            PersonDao dao = db.personDao();
            Person p1 = new Person("用户1", "男", 18);
            Person p2 = new Person("用户2", "男", 28);
            Person p3 = new Person("用户3", "男", 38);
            dao.insertPersons(p1, p2, p3);
        });
    
    }
    
    // 查询数据
    public void queryRoom(View view) {
    
        AppDatabase db = AppDatabase.getInstance(getApplicationContext());
    
        pool.execute(() -> {
    
            PersonDao dao = db.personDao();
            List<Person> list = dao.selectAllPersons();
            list.forEach(p-> Log.d("test", p.toString()));
    
        });
    }
    
    // 根据id查询
    public void queryRoomById(View view) {
    
        AppDatabase db = AppDatabase.getInstance(getApplicationContext());
    
        pool.execute(() -> {
    
            PersonDao dao = db.personDao();
            List<Person> list = dao.selectByIds(3,4);
            list.forEach(p-> Log.d("test", p.toString()));
    
        });
    }
    
    // 删除
    public void deleteRoom(View view) {
    
        AppDatabase db = AppDatabase.getInstance(getApplicationContext());
    
        pool.execute(() -> {
    
            PersonDao dao = db.personDao();
            dao.deleteByIds(1,2);
        });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
  • 相关阅读:
    【Azure 存储服务】Java Azure Storage SDK V12使用Endpoint连接Blob Service遇见 The Azure Storage endpoint url is malformed
    一文解读高压放大器
    最简单的防抖和节流
    第十五届蓝桥杯模拟考试III_物联网设计与开发
    文献阅读5
    Python学习第五篇:操作MySQL数据库
    6-TRITC 四甲基罗丹明-6-异硫氰酸 CAS 80724-20-5
    Solon v1.11.3 发布,第101个发布版本喽
    Cisco.Packet.Tracer思科模拟器路由协议优先级对照
    2000-2021年各省GDP包括名义GDP、实际GDP、GDP平减指数(以2000年为基期)
  • 原文地址:https://blog.csdn.net/wlddhj/article/details/127820069