gpt4 book ai didi

android - OnLoadFinished 无限调用

转载 作者:太空狗 更新时间:2023-10-29 13:21:08 26 4
gpt4 key购买 nike

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

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 方法,从而创建无限循环。

关于android - OnLoadFinished 无限调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28719776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com