[英]How to use Thread in cursor?
如何在Cursor
使用Thread
。 例如,我們有以下代碼:
cursor = sql.rawQuery(OUR QUERY..., null);
if (cursor.moveToFirst()) {
do {
SOME CODE....
} while (cursor.moveToNext());
}
我們可以使用嗎?
if (cursor.moveToFirst()) {
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
do {
SOME CODE....
} while (cursor.moveToNext());
}
});
thread.start();
}
您可以使用CursorLoader
而不是Thread類(如果可以,請避免使用它)。
您的Activity將實現LoaderManager.LoaderCallbacks<Cursor>
,其中包含您需要的所有回調。
然后,您需要使用其initLoader
方法初始化CursorLoader。
private static final int LOADER_ID = 1;
getLoaderManager().initLoader(LOADER_ID, null, this);
它的參數是:
int id, Bundle args, LoaderCallbacks<D> callback
ID :
此加載程序的唯一標識符。 可以隨心所欲。 標識符的作用域是特定的LoaderManager實例。
這是您使用的數字,我用過1。
束
在構造時提供給裝載機的可選參數。 如果加載程序已經存在(不需要創建新的加載程序),則將忽略此參數,並繼續使用最后一個參數。
如果您需要提供參數,那是正確的參數。
打回來
LoaderManager將調用接口以報告有關加載程序狀態的更改。 需要
這是我們的Activity類,因為它充當回調。
在此行之后,將調用onCreateLoader
,它將包含兩個參數: loaderID, bundle
我想你可以理解這是什么。
然后就是實現onCreateLoader
@Override
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle)
{
/*
* Takes action based on the ID of the Loader that's being created
*/
switch (loaderID) {
case LOADER_ID: // our ID!
// Returns a new CursorLoader
return new CursorLoader(
getActivity(), // Parent activity context
mDataUrl, // Table to query
mProjection, // Projection to return
null, // No selection clause
null, // No selection arguments
null // Default sort order
);
default:
// An invalid id was passed in
return null;
}
}
准備好后,將用光標調用onLoadFinished
,然后開始。 使用它並停止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.