Android ContentProvider CRUD Operations Example
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:
MainActivity: This activity demonstrates the CRUD operations. It initializes abookIdvariable to store the ID of the book after insertion.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.addData(Create): Inserts a new book record into the database usingcontentResolver.insert(). Theurispecifies the content provider's URI, andvaluesrepresents the data to be inserted. The inserted book's ID is retrieved from thenewUriobject.queryData(Read): Queries the database usingcontentResolver.query()to retrieve all book records. The results are iterated, and each book's details are logged.updateData(Update): Updates an existing book record usingcontentResolver.update(). It uses thebookIdto specify the book to update. Thevaluesobject contains the data to be updated.deleteData(Delete): Deletes a book record from the database usingcontentResolver.delete(). Similar toupdateData, it uses thebookIdto 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/bookURI should match the URI defined in your ContentProvider. - The code uses
contentValuesOffor creatingContentValuesobjects, 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
原文地址: https://www.cveoy.top/t/topic/qk1i 著作权归作者所有。请勿转载和采集!