我正在尝试将LiveData与Android上的Content Provider一起使用,但是由于Provider查询方法如下,因此我无法对其进行管理:
public Cursor query
因此它返回一个Cursor,而我需要一个LiveData。 如果我尝试将查询方法的返回类型更改为
public LiveData<Cursor> query
我得到了错误:
"error: query(Uri,String[],String,String[],String) in FaProvider cannot override query(Uri,String[],String,String[],String) in ContentProvider
return type LiveData<Cursor> is not compatible with Cursor"
是否有将LiveData与Content Provider一起使用的解决方案?
答案 0 :(得分:0)
应该能够将光标包裹在一个可变的实时数据对象中,例如提到的@ mohd-faizan
abstract class ContentProviderLiveData<T>(
private val context: Context,
private val uri: Uri ) : MutableLiveData<T>() {
private lateinit var observer: ContentObserver
override fun onActive() {
observer = object : ContentObserver(null) {
override fun onChange(self: Boolean) {
// Notify LiveData listeners an event has happened
postValue(getContentProviderValue())
}
}
context.contentResolver.registerContentObserver(uri, true, observer) }
override fun onInactive() {
context.contentResolver.unregisterContentObserver(observer)
}
/**
* Implement if you need to provide [T] value to be posted
* when observed content is changed.
*/
abstract fun getContentProviderValue(): T
}
更多信息: https://medium.com/@jmcassis/android-livedata-and-content-provider-updates-5f8fd3b2b3a4