处理CursorLoader异常

时间:2012-11-25 12:55:50

标签: android exception-handling android-loadermanager android-cursorloader

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

2 个答案:

答案 0 :(得分:2)

我试图继承并实现一个监听器,然后我尝试继承并实现一个回调。在我的例子中,最简单且不那么具有侵入性的解决方案似乎是以下

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();
    }
}

答案 1 :(得分: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);
    }

}

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