142
CHAPTER 8: APIs
The methods onCreateLoader(), onLoadFinished(), and onLoadReset()
describe the implementation of LoaderManager.LoaderCallbacks. Note
that the latter two are listeners, while the first one, with its name a little
confusing, is a factory method for creating loaders. The framework will
be taking care of onCreateLoader() invoked only when a loader needs
to be constructed. If a loader with some ID exists and is not abandoned,
it will be reused, and this method will not be called.
In our activity, we place the method makeLoader() to build a loader. android.content.
Loader needs to be subclassed to have a usable loader. Two implementations are
provided: android.content.AsyncTaskLoader and android.content.CursorLoader. The
loader CursorLoader can be used to load table-like content from a content provider, and
AsyncTaskLoader is more general and will be loading its data from inside an AsyncTask.
We use the latter one for the example shown here:
fun makeLoader():Loader {
val res =
@SuppressLint("StaticFieldLeak")
object : AsyncTaskLoader(this@MainActivity) {
val myData: MutableList =
ArrayList()
var initLoaded = false
override fun loadInBackground(): MyData {
Log.e("LOG",
"AsyncTaskLoader.loadInBackground()")
Log.e("LOG", "Thread: " +
Thread.currentThread().toString())
for (i in 0..9) {
Log.e("LOG", i.toString())
myData.add("Item " + i.toString())
Thread.sleep(1000)
if (isLoadInBackgroundCanceled)
throw OperationCanceledException(
"Canceled")
}
return MyData(myData)
}
override fun onStartLoading() {
Log.e("LOG",
"AsyncTaskLoader.onStartLoading()")
super.onStartLoading()
if (!initLoaded)
forceLoad()
initLoaded = true
}
}
return res
}
Do'stlaringiz bilan baham: |