I am trying to implement AsyncQueryHandler
because I am experiencing the same exact problem in this link but I dont see any example or anything about implementing it.
I tried doing
AsyncQueryHandler handler = new AsyncQueryHandler(getContentResolver());
since that is what the constructor shows in the docs but I get an error saying cannot instantiate the type AsyncQueryHandler
so how do I use it then?
AsyncQueryHandler is an abstract class, thus you cannot instantiate it directly. You need to subclass it.
It's so convenient:
AsyncQueryHandler handler =
new AsyncQueryHandler(mActivity.getContentResolver()) {};
handler.startUpdate(-1, null, sessionUri, values, null, null);
It comes very handy when you need to do CRUD operationa async without using a Loader, so by extending from asyncquery you get method such as startQuery, startInsert, startUpdate and startDelete an easy implementation could be:
public class CustomAsyncHandler extends AsyncQueryHandler {
private WeakReference<AsyncQueryListener> mListener;
public interface AsyncQueryListener {
void onQueryComplete(int token, Object cookie, Cursor cursor);
}
public CustomAsyncHandler(ContentResolver cr, AsyncQueryListener listener) {
super(cr);
mListener = new WeakReference<AsyncQueryListener>(listener);
}
public CustomAsyncHandler(ContentResolver cr) {
super(cr);
}
/**
* Assign the given {@link AsyncQueryListener} to receive query events from
* asynchronous calls. Will replace any existing listener.
*/
public void setQueryListener(AsyncQueryListener listener) {
mListener = new WeakReference<AsyncQueryListener>(listener);
}
/** {@inheritDoc} */
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
final AsyncQueryListener listener = mListener.get();
if (listener != null) {
listener.onQueryComplete(token, cookie, cursor);
} else if (cursor != null) {
cursor.close();
}
}
}
As you can see there is an extra interface AsyncQueryListener created to be as a callback when query is completed, as this you can create AsyncUpdateListener, AsyncDeleteListener, AsyncInsertListener, and so on.
AsyncQueryHandler asyncQueryHandler = new AsyncQueryHandler(activity.getContentResolver()){
@Override
protected void onInsertComplete(int token, Object cookie, Uri uri) {
super.onInsertComplete(token, cookie, uri);
Log.d(TAG, "onInsertComplete return uri: " + uri);
}
};
asyncQueryHandler.startInsert(-1, null, mUri, values);
来源:https://stackoverflow.com/questions/11961857/implementing-asyncqueryhandler