6

我有一个 Fragment 实现 LoaderManager 并使用 CursorLoader (没什么花哨的)。我想捕获查询期间抛出的异常,但我不知道怎么做!!!有什么帮助吗?谢谢。

4

2 回答 2

3

我尝试继承并实现一个监听器,然后我尝试继承并实现一个回调。就我而言,最简单且侵入性较小的解决方案似乎如下

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();
    }
}
于 2012-12-06T21:54:48.790 回答
1

您需要从 CursorLoader 派生来执行此操作。像这样的东西:

class MyCursorLoader extends CursorLoader {

    public MyCursorLoader(Context context) {
         super(context)
      }

    public CursorLoader(Context context, Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        super(context, uri, projection, selection, selectionArgs, sortOrder);
    }

    @Override
    public Cursor loadInBackground() {

        try {
            return (super.loadInBackground);
        } catch (YourException e) {
            // Do your thing.
        }

        return (null);
    }

}

您可以对其进行调整以实现错误处理。

于 2012-12-05T18:39:10.173 回答