Android studio 数据库(内容提供器)

工程一:

<provider
    android:name=".MyContentProvider"
    android:authorities="com.example.xryapplication8.provider"
    android:enabled="true"
    android:exported="true"></provider>

ContentProvider:

class MyContentProvider : ContentProvider() {

    private val studentDir = 0
    private val studentItem = 1
    private val authority = "com.example.xryapplication8.provider"
    private var dbHelper : MyDatabaseHelper ?= null

    private val uriMatcher by lazy {
        val matcher = UriMatcher(UriMatcher.NO_MATCH)
        matcher.addURI(authority,"student",studentDir)
        matcher.addURI(authority,"student/#",studentItem)
        matcher
    }
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = dbHelper?.let {

        val db = it.writableDatabase
        val deletedRows = when(uriMatcher.match(uri)){
            studentDir -> db.delete("Student",selection,selectionArgs)
            studentItem -> {
                val studentId = uri.pathSegments[1]
                db.delete("Student","id = ?", arrayOf(studentId))
            }
            else -> 0
        }
        deletedRows
    }?:0

    override fun getType(uri: Uri) =  when(uriMatcher.match(uri)) {
        studentDir -> "vnd.android.cursor.dir/vnd.com.example.xryapplication8.provider.student"
        studentItem -> "vnd.android.cursor.item/vnd.com.example.xryapplication8.provider.student"
        else -> null
    }

    override fun insert(uri: Uri, values: ContentValues?) = dbHelper?.let {
        val db = it.writableDatabase
        val uriReturn = when(uriMatcher.match(uri)){
            studentDir,studentItem->{
                val newStuId = db.insert("Student",null,values)
                Uri.parse("content://$authority/student/$newStuId")
            }
            else -> null
        }
        uriReturn
    }

    override fun onCreate() = context?.let{
        dbHelper = MyDatabaseHelper(it,"Student.db",2)
        true
    } ?:false

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    )= dbHelper ?.let {
        val db = it.readableDatabase
        val cursor = when(uriMatcher.match(uri)){
            studentDir -> db.query("Student",projection,selection,selectionArgs,null,null,sortOrder)
            studentItem -> {
                val stuId = uri.pathSegments[1]
                db.query("Student",projection,"id= ?", arrayOf(stuId),null,null,sortOrder)
            }
            else -> null
        }
        cursor
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?,
        selectionArgs: Array<String>?
    )= dbHelper?.let {
       val db = it.writableDatabase
        val updatedRows = when(uriMatcher.match(uri)){
            studentDir ->db.update("Student",values,selection,selectionArgs)
            studentItem -> {
                val studentId  = uri.pathSegments[1]
                db.update("Student",values,"id=?", arrayOf(studentId))
            }
            else ->0
        }
        updatedRows
    }?:0

}

database:

class MyDatabaseHelper(val context: Context,name:String,version:Int) : SQLiteOpenHelper(context,name,null,version) {
    private val createStudent = "create table Student (" +
            "id integer primary key," +
            "name text," +
            "college  text,"+
            "age integer,"+
            "phone integer)"

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(createStudent)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        db?.execSQL("drop table if exists Student")
        onCreate(db)
    }

}

工程2:

插入:

class xryActivity1 :AppCompatActivity() ,View.OnClickListener{

    var stuId:String?=null
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_xry1)
        val button:Button = findViewById(R.id.button)
        button.setOnClickListener (this)
    }

    override fun onClick(v: View?) {//增加
        val uri = Uri.parse("content://com.example.xryapplication8.provider/student")
        val editText1 : EditText = findViewById(R.id.editTextid)
        val editText2 : EditText = findViewById(R.id.editTextname)
        val editText3 : EditText = findViewById(R.id.editTextcollege)
        val editText4 : EditText = findViewById(R.id.editTextage)
        val editText5 : EditText = findViewById(R.id.editTextphone)
        when(v?.id){
            R.id.button -> {
                val inputText1 = editText1.text.toString()
                val inputText2 = editText2.text.toString()
                val inputText3 = editText3.text.toString()
                val inputText4 = editText4.text.toString()
                val inputText5 = editText5.text.toString()
                val values = contentValuesOf("id" to inputText1,"name" to inputText2,
                "college" to inputText3,"age" to inputText4,"phone" to inputText5)
                val newUri = contentResolver.insert(uri,values)
                stuId = newUri?.pathSegments?.get(1)

                val intent = Intent(this,MainActivity::class.java)
                startActivityForResult(intent,1)
            }


        }
    }
}

查询:
 

class xryActivity2 :AppCompatActivity(),AdapterView.OnItemClickListener {
    private val list = ArrayList<student>()

    @SuppressLint("Range")
    override fun onCreate(savedInstanceState:Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recyclerview)
        val listview:ListView = findViewById(R.id.listView)
        val adapter = StuAdapter(R.layout.item,list,this)
        listview.adapter = adapter


        listview.setOnItemClickListener(this)

        val uri = Uri.parse("content://com.example.xryapplication8.provider/student")
        contentResolver.query(uri,null,null,null,null)?.apply {
            while(moveToNext()){//查找
                val name = getString(getColumnIndex("name"))
                val id = getInt(getColumnIndex("id"))
                val college = getString(getColumnIndex("college"))
                val stu = student(name, id, college)
                list.add(stu)
            }
            close()
        }
    }
    
    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val stus = list[position]

        val intent = Intent(this,xryActivity3::class.java)
        intent.putExtra("stu_id",stus.id.toString())
        startActivity(intent)
    }
    
}

修改和删除:

class xryActivity3 :AppCompatActivity(),View.OnClickListener{

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_xry3)
        val button1 :Button = findViewById(R.id.button01)
        button1.setOnClickListener(this)
        val button2: Button = findViewById(R.id.button02)
        button2.setOnClickListener(this)

        val textView:TextView = findViewById(R.id.textViewid)
        textView.text = intent.getStringExtra("stu_id").toString()
    }


    override fun onClick(v: View?) {
        val studentId = intent.getStringExtra("stu_id")
        val textView:TextView =findViewById(R.id.textViewid)
        textView.text=studentId
        val editText1: EditText = findViewById(R.id.editTextname)
        val editText2: EditText = findViewById(R.id.editTextcollege)
        val editText3: EditText = findViewById(R.id.editTextage)
        val editText4: EditText = findViewById(R.id.editTextphone)
       when(v?.id){

           R.id.button01 ->{//修改
              studentId?.let {
                  val inputText1 = editText1.text.toString()
                  val inputText2 = editText2.text.toString()
                  val inputText3 = editText3.text.toString()
                  val inputText4 = editText4.text.toString()
                  val uri = Uri.parse("content://com.example.xryapplication8.provider/student/$it")
                  val values = contentValuesOf("name" to inputText1,"college" to inputText2,
                  "age" to inputText3,"phone" to inputText4)
                  contentResolver.update(uri,values,null,null)
                  val intent = Intent(this,xryActivity2::class.java)
                  startActivityForResult(intent,1)
              }
           }
           R.id.button02 ->{//删除
               studentId?.let {
                   val uri = Uri.parse("content://com.example.xryapplication8.provider/student/$it")
                   contentResolver.delete(uri,null,null)
                   val intent = Intent(this,xryActivity2::class.java)
                   startActivityForResult(intent,1)
               }
           }
       }
    }
}

student:

class student (var name:String,var id:Int,var college:String)

Adapter:

class StuAdapter(var resourceId:Int,var stulist:ArrayList<student>,var context: Context):
    BaseAdapter() {
    @SuppressLint("MissingInflatedId")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var v: View = LayoutInflater.from(context).inflate(R.layout.item, null)
        val model: student = stulist[position]
        val name: TextView = v.findViewById(R.id.studentname)
        val id: TextView = v.findViewById(R.id.studentid)
        val college: TextView = v.findViewById(R.id.studentcollege)
        name.text = model.name
        id.text = model.id.toString()
        college.text = model.college
        return v


    }

    override fun getCount(): Int {
        return stulist.size
    }

    override fun getItem(position: Int): student? {
        return stulist[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值