android - OnLoadFinished 无限调用

标签 android android-contentprovider loader

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

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/

相关文章:

android - 当 is_primary 标志在 android 联系人中设置为非零值时?

ios - 关于ios Application loader代码设计验证

android - Geocode 服务在真实设备上不存在,我该如何解决?

java - 为什么我不能在 JAVA 方法中使用变量?

android - 我应该使用内容提供商吗?

java - 反序列化二进制类文件的内容时出现 ClassNotFoundException

android - 从 SharedPreferences 中删除条目后未通知 OnSharedPreferenceChangeListener

android - 如何更改 DatePickerDialog 中 NumberPickers 的顺序

android - 获取值以在 Android 应用程序中以不同语言显示 - 本地化

android - 在 Android 5.0 中查询从联系人中获取电子邮件?崩溃