Fork me on GitHub

【Kotlin】基于Room对SQLite操作

gradle中添加引用 一下引用有重复,可以删除部分,我这个在项目中,懒得删除了

def room_version = "2.3.0"
    implementation 'androidx.room:room-common:2.3.0'
    implementation 'androidx.room:room-runtime:2.3.0'
    annotationProcessor 'androidx.room:room-compiler:2.3.0'
//其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如4.0.3
//    implementation 'com.tencent.rqd:nativecrashreport:latest.release' //其中latest.release指代最新Bugly NDK版本号,也可以指定明确的版本号,例如3.9.2


    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // To use Kotlin annotation processing tool (kapt)
    kapt "androidx.room:room-compiler:$room_version"

  定义实体,也就是表

@Entity(tableName = "t_avail_data")
data class AvailDataEntity(
    @PrimaryKey(autoGenerate = true)  val id: Int,
    @ColumnInfo(name="created_at") val created_at: String
)

  定义操作接口

@Dao
open interface BaseKotlinDao<T> {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg operations: T);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(operation: T);

    @Delete
    fun delete(operation: T);

    @Update
    fun update(operation: T);

    open fun getAll(): List<T>;

}

  定义具体业务接口

  

@Dao
interface AvailDataDao: BaseKotlinDao<AvailDataEntity> {
    /**
     * 获取所有
     */
    @Query("SELECT * from t_avail_data")
    override fun getAll(): List<AvailDataEntity> ;

    /**
     * 根据Rrid 获取
     */
    @Query("SELECT * from t_avail_data WHERE id=(:id) Limit 1")
    fun getById(id:Int): AvaidDataEntity;

    /**
     * 清空表
     */
    @Query("delete from t_avail_data")
    fun clean();
}

  定义DataBase

@Database(entities = {AvalidDataEntity.class}, version = 1, exportSchema = false)
public abstract class AppDataBase extends RoomDatabase {

  public  AvalidDataDao avalidDataDao();
}

  创建DbUtil

public class DbUtil {

    private static AppDataBase db = null;
    private static Context context = ContextUtils.getApplicationContext();


    public static AppDataBase getDb() {
        if (db == null) {
            db = Room.databaseBuilder(context,
                    AppDataBase.class, "icebox-system-06").allowMainThreadQueries().fallbackToDestructiveMigration().build();
        }
        return db;
    }

    public static void setContext(Context context) {
        DbUtil.context = context;
    }


    public static void setPopupWindowTouchModal(PopupWindow popupWindow, boolean touchModal) {
        if (null == popupWindow) {
            return;
        }
        Method method;
        try {
            method = PopupWindow.class.getDeclaredMethod("setTouchModal", boolean.class);
            method.setAccessible(true);
            method.invoke(popupWindow, touchModal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  上下文工具ContextUtils

public class ContextUtils {
    private static Context applicationContext = null;

    public static Context getApplicationContext() {
        if (null != applicationContext) {
            return applicationContext;
        }

        final Object activityThread = getActivityThread();
        if (null != activityThread) {
            try {
                final Method getApplication = activityThread.getClass().getDeclaredMethod("getApplication");
                getApplication.setAccessible(true);
                applicationContext = (Context) getApplication.invoke(activityThread);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return applicationContext;
    }

    private static Object getActivityThread() {
        try {
            final Class<?> clz = Class.forName("android.app.ActivityThread");
            final Method method = clz.getDeclaredMethod("currentActivityThread");
            method.setAccessible(true);
            final Object activityThread = method.invoke(null);
            return activityThread;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

  

使用的例子后面补充

 

posted @ 2023-07-13 02:14  黄高林  阅读(116)  评论(0编辑  收藏  举报