This Android code demonstrates how to perform CRUD operations (Create, Read, Update, Delete) on a database using a ContentProvider. The example focuses on a book database with fields for 'name', 'author', 'pages', and 'price'.

Code Breakdown:

class MainActivity() : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    var bookId: String? = null


    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding=ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.addData.setOnClickListener {
            // 添加数据
            val uri = Uri.parse("content://com.example.databasetest1.provider/book")
            val values = contentValuesOf("name" to "A Clash of Kings",
                "author" to "George Martin", "pages" to 1040, "price" to 22.85)
            val newUri = contentResolver.insert(uri, values)
            bookId = newUri?.pathSegments?.get(1)
        }
        binding.queryData.setOnClickListener {
            // 查询数据
            val uri = Uri.parse("content://com.example.databasetest1.provider/book")
            contentResolver.query(uri, null, null, null, null)?.apply {
                while (moveToNext()) {
                    val name = getString(getColumnIndex("name"))
                    val author = getString(getColumnIndex("author"))
                    val pages = getInt(getColumnIndex("pages"))
                    val price = getDouble(getColumnIndex("price"))
                    Log.d("MainActivity", "book name is '$name'")
                    Log.d("MainActivity", "book author is '$author'")
                    Log.d("MainActivity", "book pages is $pages")
                    Log.d("MainActivity", "book price is $price")
                }
                close()
            }
        }
        binding.updateData.setOnClickListener {
            // 更新数据
            bookId?.let {
                val uri = Uri.parse("content://com.example.databasetest1.provider/ book/$it")
                val values = contentValuesOf("name" to "A Storm of Swords",
                    "pages" to 1216, "price" to 24.05)
                contentResolver.update(uri, values, null, null)
            }
        }
        binding.deleteData.setOnClickListener {
            // 删除数据
            bookId?.let {
                val uri = Uri.parse("content://com.example.databasetest1.provider/ book/$it")
                contentResolver.delete(uri, null, null)
            }
        }
    }
}

Explanation:

  1. MainActivity: This activity demonstrates the CRUD operations. It initializes a bookId variable to store the ID of the book after insertion.
  2. onCreate: This method is called when the activity is created. It inflates the layout, sets up the click listeners for buttons, and defines the logic for each operation.
  3. addData (Create): Inserts a new book record into the database using contentResolver.insert(). The uri specifies the content provider's URI, and values represents the data to be inserted. The inserted book's ID is retrieved from the newUri object.
  4. queryData (Read): Queries the database using contentResolver.query() to retrieve all book records. The results are iterated, and each book's details are logged.
  5. updateData (Update): Updates an existing book record using contentResolver.update(). It uses the bookId to specify the book to update. The values object contains the data to be updated.
  6. deleteData (Delete): Deletes a book record from the database using contentResolver.delete(). Similar to updateData, it uses the bookId to identify the book to delete.

Important Notes:

  • You need to have a custom ContentProvider implemented to handle the database interactions. This code assumes you have a working ContentProvider set up.
  • The content://com.example.databasetest1.provider/book URI should match the URI defined in your ContentProvider.
  • The code uses contentValuesOf for creating ContentValues objects, which is a Kotlin extension function.

This example provides a fundamental understanding of how to utilize ContentProvider to manage data in your Android applications. It demonstrates the core CRUD operations and serves as a starting point for more complex data management tasks. Remember to adapt and customize the code to fit your specific needs and data models.

For further exploration, you can research:

  • ContentProvider for advanced query operations and data management
  • ContentProvider for accessing system data
  • Using ContentObserver to monitor data changes
  • Handling permission requests for accessing ContentProvider
Android ContentProvider CRUD Operations Example

原文地址: https://www.cveoy.top/t/topic/qk1i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录