kotlin ContentProvider

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"))
            }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值