我正在创建一个新的示例Android应用程序,其中包含一个 Activity 和许多片段。

首先,我要启动“OverviewFragment”(我的仪表板),其中应显示一些基本信息。我的OverviewFragment使用“AccountProvider”(ContentProvider)加载信息。如果数据库为空,则应该用我的WelcomeFragment替换OverviewFragment ...

这是一些代码:

public class OverviewFragment extends BaseFragment
    implements LoaderManager.LoaderCallbacks {

private static final int LOADER_ACCOUNTS = 10;
private static final int LOADER_TRANSACTIONS = 20;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getLoaderManager().initLoader(LOADER_ACCOUNTS, null, this);
    //getLoaderManager().initLoader(LOADER_TRANSACTIONS, null, this);
}

@Override
public Loader onCreateLoader(int id, Bundle args) {
    Uri uri = null;
    String[] projection = null;
    String selection = null;
    String[] selectionArgs = null;
    String sortOrder = null;

    switch (id) {
        case LOADER_ACCOUNTS:
            uri = WalletProvider.CONTENT_URI;
            projection = new String[]{DBHelper.ACC_ID, DBHelper.ACC_TITLE};
            sortOrder = DBHelper.ACC_TITLE;
            break;
    }
    CursorLoader cl =  new CursorLoader(getActivity(),
            uri, projection, selection, selectionArgs, sortOrder);
    return cl;
}

@Override
public void onLoadFinished(Loader loader, Object data) {
    switch (loader.getId()) {
        case LOADER_ACCOUNTS:
            bindAccounts((Cursor) data);
            break;
    }

}

@Override
public void onLoaderReset(Loader loader) {

}

private void bindAccounts(Cursor cursor) {
    boolean showCreateWallet = true;


    if (cursor != null && cursor.moveToFirst()) {
        showCreateWallet = false;
    }

    if (showCreateWallet) {
        listener.changeFragment(new WalletCreateFragment());
    }
}

这是我的主要 Activity
    @Override
public void changeFragment(Fragment fragmentToLoad) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, fragmentToLoad)
            .commit();
}

现在...如果我用一个空的数据库启动我的应用程序,我会收到您在标题中看到的错误。

我知道我不应该在onLoadFinished函数中更改片段....但是我可以在哪里做呢? :P

对不起,我的英语=)

最佳答案

这是android的错误。要解决此问题,请使用Handler替换/添加/调用onLoadFinished内部的Fragment,如下所示:

final int WHAT = 1;
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == WHAT) changeFragment(fragmentToLoad);
    }
};
handler.sendEmptyMessage(WHAT);

10-07 22:07