Search code examples
androidandroid-contentproviderloader

OnLoadFinished called infinitely


Yesterday I try to write my content provider and to test it. Unfortunately, this piece of code:

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

does something, because of which onLoadFinished is called infinitely. Has someone idea what is going on? When I remove it onLoadFinished is called only once. And when onLoaderReset is called ? Can someone give me an real example to test it? Thanks in advance.

Thas is the all code for the loader:

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

And I set onClickListener of one of my buttons:

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

I just try that and I don't know why onLoadFinished is called infinitely times.


Solution

  • As per the 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.

    That being said, when you are calling

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

    Inside the onLoadFinished, you are triggering the onLoadFinished method again, creating an indefinite loop.