Android本地数据存储常用的有三种方式1、SP存储,key-value的方式存储在本地的xml文件中,/data/data/xxx.xx/shared_prefs/xxx.xml ,下面我们就来说一说关于android中的五大存储数据方式?我们一起去了解并探讨一下这个问题吧!

android中的五大存储数据方式(Android本地数据存储SPSQLite)

android中的五大存储数据方式

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

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

2、SQLite存储

3、room存储

一、SP存储使用

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

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

该方法需要传入两个参数

  1. MODE_PRIVATE:只有本应用程序才可以对这个文件进行读写
  2. MODEWORLDREADABLE:其他应用对这个 SharedPreferences 文件只能读不能修改
  3. MODEWORLDWRITEABLE:这个 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();//提交数据保存

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);

二、SQLite存储使用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) { } }

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(); }

方法二,执行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(); }

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(); }

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(); }

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(); }

方法二,执行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(); }

三、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、@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; }

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(); }

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; } }

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); }); }

,