title: Best practices to query SQLite database in ListFragment with CursorLoader?
body: <p>I'm using Android Compatibility Library in my project. I've set up ListFragment as described in the DevGuide (<a href="http://developer.android.com/reference/android/app/Fragment.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/app/Fragment.html</a>), and using a simple CursorLoader Christian made be used without content provider (<a href="https://stackoverflow.com/questions/7182485/usage-cursorloader-without-contentprovider/7422343#7422343">CursorLoader usage without ContentProvider</a>).</p>
  
  <p><strong>The question is</strong> where, in my ListFragment / parent Activity, should I open database, return the Cursor, create Adapter and setListAdapter?</p>
  
  <p>So in my app, I have TitlesFragment, DetailsFragment, FragmentLayoutActivity, DetailsLayoutActivity.</p>
  
  <p>Is the best practice...</p>
  
  <ul>
  <li><p>to open database in ListFragment's <code>onActivityCreated</code>and close it in ListFragment's <code>onDestroy</code> like in code sample below</p>
  
  <pre><code>@Override
  public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      // Open database
      playersDatabaseHelper = new PlayersDBAdapter(getActivity());
      playersDatabaseHelper.open();
      getLoaderManager().initLoader(0, null, this);
      ...
  }
  
  @Override
  public void onDestroy() {
      super.onDestroy();
      if (playersDatabaseHelper != null) {
          playersDatabaseHelper.close();
      }
  }
  </code></pre></li>
  <li><p>query database and return the cursor in <code>onCreateLoader</code>, and create the Adapter and setListAdapter in <code>onLoadFinished</code> like in code sample below</p>
  
  <pre><code>@Override
  public Loader&lt;Cursor&gt; onCreateLoader(int id, Bundle args) {
      // Now create and return a CursorLoader that will take care of
      // creating a Cursor for the data being displayed.
      return new MyCursorLoader(getActivity()) {
          @Override
          public Cursor loadInBackground() {
              playersCursor = playersDatabaseHelper.getAllPlayers();
              return playersCursor;
          }
      };
  
  }
  
  @Override
  public void onLoadFinished(Loader&lt;Cursor&gt; loader, Cursor cursor) {      
      // Create an empty adapter we will use to display the loaded data.
      playersAdapter = new RowAdapter(getActivity(), playersCursor, R.layout.players_overview_row);
  
      // Allocate the adapter to the List displayed within this fragment.
      setListAdapter(playersAdapter);
  
      playersAdapter.swapCursor(cursor);
  
      // The list should now be shown.
      if (isResumed()) {
          setListShown(true);
      } else {
          setListShownNoAnimation(true);
      }
  }
  </code></pre></li>
  </ul>
  
  <p>Am I on the right track or should I move some of those somewhere? Thanks for your time!</p>