Skip to main content

Best practices to query SQLite database in ListFragment with CursorLoader?



I'm using Android Compatibility Library in my project. I've set up ListFragment as described in the DevGuide ( http://developer.android.com/reference/android/app/Fragment.html ), and using a simple CursorLoader Christian made be used without content provider ( Usage CursorLoader without ContentProvider ).





The question is where, in my ListFragment / parent Activity, should I open database, return the Cursor, create Adapter and setListAdapter?





So in my app, I have TitlesFragment, DetailsFragment, FragmentLayoutActivity, DetailsLayoutActivity.





Is the best practice...









  • to open database in ListFragment's onActivityCreated and close it in ListFragment's onDestroy like in code sample below







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

    }

    }











  • query database and return the cursor in onCreateLoader , and create the Adapter and setListAdapter in onLoadFinished like in code sample below







    @Override

    public Loader<Cursor> 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<Cursor> 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);

    }

    }











Am I on the right track or should I move some of those somewhere? Thanks for your time!



Source: Tips4all

Comments

  1. Sorry no experience in CursorLoader yet and Fragment, but I already experienced use of SQLiteOpenHelper in the context of concurrent access by different threads & activities.

    I will assume that PlayersDBAdapter is internally using a SQLiteOpenHelper class. but it is not clear what your methods open() and close() are doing?

    What I did:


    define your SQLiteOpenHelper as an application wide singleton, not activity wide as you seem to do
    instantiate SQLiteOpenHelper single instance in your Application onCreate
    DON'T release SQLiteOpenHelper instance in any activity onDestroy, as when an activity stops, another one might still have to open the DB
    I guess SQLiteOpenHelper instance should be cleared in application onTerminate (not sure as onTerminate is in practice almost never called)
    I have DBAdapter object which gets a SQLiteDatabase reference with mySQLiteOpenHelper.getWritableDatabase()
    these DBAdapter are typically allocated in activity onCreate and released in onDestroy


    At least this works, no crashs in an application with several thousands users.
    Suggestions to improve that are welcome :-)

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.