OnLoadFinished 无限调用

OnLoadFinished called infinitely

昨天我尝试编写我的内容提供程序并对其进行测试。不幸的是,这段代码:

if(loader.getId() == 1)       
 getContentResolver().insert(Uri.parse("content://com.example.djak.contentprovidertest.provider/cte"), values);

做某事,因此无限调用 onLoadFinished。有人知道发生了什么事吗?当我删除它时,onLoadFinished 只被调用一次。 什么时候调用 onLoaderReset ?有人可以给我一个真实的例子来测试吗? 提前致谢。

加载器的全部代码如下:

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    loader = new CursorLoader(this, Uri.parse("content://com.example.djak.contentprovidertest.provider/cte"),
            null, null, null, null);


    Log.d("Some looong data", "Create");

    return loader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    ContentValues values = new ContentValues();
    values.put("user", "s");


    if(loader.getId() == 1) getContentResolver().insert(Uri.parse("content://com.example.djak.contentprovidertest.provider/cte"), values);

    Log.d("Some looong data", "Finish");


}


@Override
public void onLoaderReset(Loader<Cursor> loader) {
    Toast.makeText(this, "RESET", Toast.LENGTH_SHORT).show();
}

然后我设置了其中一个按钮的 onClickListener:

       findViewById(R.id.temp_button).setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           getLoaderManager().initLoader(1, null, MainActivity.this);
       }
   });

我只是试了一下,我不知道为什么会无限次调用 onLoadFinished。

根据 official documentation

The Loader will monitor for changes to the data, and report them to you through new calls here. (here = onLoadFinished method) You should not monitor the data yourself. For example, if the data is a Cursor and you place it in a CursorAdapter, use the CursorAdapter(android.content.Context, android.database.Cursor, int) constructor without passing in either FLAG_AUTO_REQUERY or FLAG_REGISTER_CONTENT_OBSERVER (that is, use 0 for the flags argument). This prevents the CursorAdapter from doing its own observing of the Cursor, which is not needed since when a change happens you will get a new Cursor throw another call here.

也就是说,当您打电话时

if(loader.getId() == 1) getContentResolver().insert(Uri.parse("content://com.example.djak.contentprovidertest.provider/cte"), values); 

onLoadFinished 中,您再次触发了 onLoadFinished 方法,创建了一个无限循环。