kotlin ContentProvider
SQLiteOpenHelper
public class MySqlite extends SQLiteOpenHelper {
public MySqlite( Context context) {
super(context, "User_Foods", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table user(id integer primary key autoincrement ,title varchar(50) ,collect_num varchar(50) ,food_title varchar(50) ,type varchar(20) , pic varchar(100) , phone varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
ContentProvider
class MyContentProvider : ContentProvider() {
var db: SQLiteDatabase ?= null
override fun onCreate(): Boolean {
var mySqlite:MySqlite = MySqlite(context)
db = mySqlite.writableDatabase
if (db==null){
return false
}else{
return true
}
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
return db!!.delete("user",selection,selectionArgs)
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
db!!.insert("user",null,values)
return uri
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?
): Cursor? {
return db?.query("user",projection,selection,selectionArgs,null,null,sortOrder)
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
return db!!.update("user",values,selection,selectionArgs)
}
}
清单文件注册
<provider
android:name=".molder.db.MyContentProvider"
android:authorities="myprovider"
android:enabled="true"
android:exported="true">
</provider>
查询数据库
var uri=Uri.parse("content://myprovider")
var db= contentResolver
var query = db!!.query(uri, arrayOf("id", "title","collect_num","food_title","type","pic","phone") ,null, null, null)
while (query.moveToNext()){
val id = query.getInt(query.getColumnIndex("id"))
var title = query.getString(query.getColumnIndex("title"))
val collect_num = query.getString(query.getColumnIndex("collect_num"))
val food_title = query.getString(query.getColumnIndex("food_title"))
val type = query.getString(query.getColumnIndex("type"))
val pic = query.getString(query.getColumnIndex("pic"))
val phone = query.getString(query.getColumnIndex("phone"))
}