Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android room数据库使用

Android room数据库使用详解

作者:baidu_24743861

这篇文章主要介绍了Android room数据库使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1、引入库

 def room_version = "2.3.0"
    implementation "androidx.room:room-runtime:$room_version"
    // For Kotlin use kapt instead of annotationProcessor
    annotationProcessor "androidx.room:room-compiler:$room_version"
    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"
    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

2.AppDatabase类

@Database(entities = {
        //用户信息
        UserInfo.class
        }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase instance;
 
    public static synchronized AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context, AppDatabase.class, 
                      //数据库存放在SD卡
                     FileUtils.getDatabasePath("test.db"))
                    //.addMigrations(MIGRATION_1_2)
                    .build();
        }
        return instance;
    }
 
    public abstract RoomDao roomDao();
 
    //进行数据库升级
    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //在这里用sql脚本完成
            database.execSQL("alter table user add column flag integer not null default 1");
        }
    };
}
public class FileUtils {
 
    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists())
            file.delete();
    }
 
    /**
     * 获得数据库路径,如果不存在,则创建对象对象
     *
     * @param name
     */
    public static String getDatabasePath(String name) {
        //判断是否存在sd卡
        boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
        if (!sdExist) {//如果不存在,
            Log.e("SD卡管理:", "SD卡不存在,请加载SD卡");
            return null;
        } else {//如果存在
            //获取sd卡路径
            String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
            dbDir += "/database";//数据库所在目录
            String dbPath = dbDir + "/" + name;//数据库路径
            LogUtil.d("dbPath:" + dbPath);
            return dbPath;
        }
    }
}

3.用户表

@Entity(tableName = "user")
public class UserInfo extends BaseBean {
    @NonNull
    @PrimaryKey
    private String userId;
    private String name;//用户名
    private String headImg;
    private String pwd;
    private String createTime;
    @Ignore
    private boolean isSelect;
 
    public UserInfo() {
    }
 
    @Ignore
    public UserInfo(String userId, String name, String headImg, String pwd) {
        this.userId = userId;
        this.name = name;
        this.headImg = headImg;
        this.pwd = pwd;
    }
 
 
    public String getUserId() {
        return userId;
    }
 
    public void setUserId(String userId) {
        this.userId = userId;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
 
    public String getHeadImg() {
        return headImg;
    }
 
    public void setHeadImg(String headImg) {
        this.headImg = headImg;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public boolean isSelect() {
        return isSelect;
    }
 
    public void setSelect(boolean select) {
        isSelect = select;
    }
 
    public String getCreateTime() {
        return createTime;
    }
 
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
}

4.RoomDao

@Dao
public interface RoomDao {
    /**
     * 插入用户
     *
     * @param user
     */
    @Insert
    void insertUser(UserInfo user);
 
    //如果插入的新数据在表中已经存在,即如果遇上数据冲突的情况,新数据直接替换旧数据;
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(UserInfo... user);
 
    @Update
    void updateUser(UserInfo note);
 
    /**
     * 获取所有的用户
     *
     * @return
     */
    @Query("SELECT * FROM user")
    LiveData<List<UserInfo>> getUserList();
 
    /**
     * 根据用户名查询用户
     *
     * @param userName
     * @return
     *
    @Query("SELECT * FROM user WHERE name = :userName LIMIT 1")
    LiveData<UserInfo> findUserByName(String userName);
    /**
     * 根据userId查询用户
     */
    @Query("SELECT * FROM user WHERE userId = :userId LIMIT 1")
    LiveData<UserInfo> findUserById(String userId);
}

5.Repository 

public class Repository {
 
    private final AppDatabase appDB;
 
    public Repository(Context context) {
        appDB = AppDatabase.getInstance(context);
    }
 
    /**
     * 插入用户
     *
     * @param user
     */
    public void insertUser(final UserInfo user) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                appDB.roomDao().insertUser(user);
                return null;
            }
        }.execute();
    }
 
    /**
     * 获取所有的用户信息
     *
     * @return
     */
    public LiveData<List<UserInfo>> getUserList() {
        return appDB.roomDao().getUserList();
    }
 
    /**
     * 根据用户名查询用户
     */
    public LiveData<UserInfo> findUserByName(String name) {
        return appDB.roomDao().findUserByName(name);
    }
 
    /**
     * 根据userId查询用户
     */
    public LiveData<UserInfo> findUserById(String userId) {
        return appDB.roomDao().findUserById(userId);
    }
}

6.使用

Repository repository = new Repository(context);
 
 repository.getUserList().observe(this, new Observer<List<UserInfo>>() {
            @Override
            public void onChanged(List<UserInfo> userList) {
                mUserList = userList;
                LogUtil.d("mUserList个数:" + mUserList.size());
                if (mUserList.size() > 0) {
                    mAdapter.setList(userList);
                }
            }
        });

到此这篇关于Android room数据库使用的文章就介绍到这了,更多相关Android room数据库使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文