我尝试继承并实现一个侦听器,然后尝试继承并实现一个回调。就我而言,最简单且侵入性较小的解决方案似乎如下
public class CursorLoaderGraceful extends CursorLoader {
public Throwable error; // holder
public CursorLoaderGraceful(Context context) {
super(context);
}
public CursorLoaderGraceful(Context context, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
super(context, uri, projection, selection, selectionArgs, sortOrder);
}
public void OnQueryException(RuntimeException throwable) {
throw throwable;
}
@Override
public Cursor loadInBackground() {
try {
return (super.loadInBackground());
} catch (Throwable t) {
error = t; // keep it
}
return (null);
}
}
在片段/活动中
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoaderGraceful loader = new CursorLoaderGraceful(this., other, params, go , here);
// ...
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//trivial code
mAdapter.swapCursor(data);
if (this.isResumed()) {
this.setListShown(true);
} else {
this.setListShownNoAnimation(true);
}
//check and use
Throwable loaderError = ((CursorLoaderGraceful)loader).error;
if (loaderError != null) {
//all these just to show it?!?!? :/
Toast.makeText(this, loaderError.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}