1.先在SQLite資料庫上自己創建規律的可擴展二級串列資料,如下圖:

2. 做的專案如下圖:

3.在AndroidManifest.xml中修改默認的Application為我們的MyApplication類
<application
android:name="com.demo.test3.MyApplication"//添加這一句
3.1 MyApplication.kt
......
override fun onCreate() {
super.onCreate()
instance = this
context = applicationContext
dbName = "test.db"//sqlite的db檔案表名:test.db
AppUtils.copyDbFileFromAsset(context, dbName)
}
......
3.1.1 AppUtils.kt
/**
* 復制離線庫檔案到 databases 目錄
*/
fun copyDbFileFromAsset(context: Context, dbName: String) {
var `is`: InputStream
var os: OutputStream
val dbDir = File(context.filesDir.parent + "/databases")
if (!dbDir.exists()) {
dbDir.mkdir()
}
var outDbFile: File
outDbFile = File(dbDir, dbName)
try {
os = FileOutputStream(outDbFile)
val buffer = ByteArray(1024)
var length: Int
`is` = context.assets.open(dbName)
while (`is`.read(buffer).also {
length = it
} > 0) {
os.write(buffer, 0, length)
}
os.flush()
`is`.close()
os.close()
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
4.MainActivity.kt,list獲取組數和子選項
val query = DaoFactory.daoFactory.getSitCodeDao().queryBuilder().orderAsc(SitCodeDao.Properties.Code).build()
val list: List<SitCode> = query.list()
5.SitCodeDao.java
public static final String TABLENAME = "MyTest";//db檔案的表名
public static class Properties {
public final static Property Id = new Property(0, String.class, "id", false, "id");
public final static Property Code = new Property(1, String.class, "code", false, "code");
public final static Property Name = new Property(2, String.class, "name", false, "name");
}
6.源代碼zip下載:
下載源代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/290908.html
標籤:其他
