Wednesday, February 11, 2015

MyNotes: Creating the Data Access Layer in the Common Library.

To start work on the data access layer I need to setup some common classes to make it easier for this app and future apps.

Manage the UI Thread

Since my access layer will be available to any area of the app, I have to worry about my threads more than I would if I was using a ContentProvider.

Prior to Lollipop, Android apps are single threaded by default.   This is often called the UI thread. However, Lollipop added a RenderThread that handles animations to make the smoother.  By default, your app will still perform all work (except animations) on the UI thread unless told to so otherwise. 

In either case, accessing the database on the UI thread is very bad.  You should never do any potentially long-lived operation on the UI thread because it will degrade your UI performance and might lead to an Android Not Responding error.

In order to prevent this, I created a class, ThreadCheck, that validates which thread is running during a method.  I will add a check to each method that access the database to verify that it is not running on the UI thread.  If it is on the UI thread, it will throw a special exception, ThreadException. This will drive out any threading issues quickly and early on.  

To check if a method is called on the UI thread is very easy.  You just have to call Looper.getMainLooper().getThread().  The MainLooper is always associated with the main thread, which happens to always be the UI thread.

Common Ways to Update Items in the Database

Now I need a common approach to updating items in the database.  This is done with an interface, DatabaseStorable, and a Utility class, DatabaseUtilities.  The DatabaseStorable contains methods to store or remove a single item from the database.  Any item that is backed by the database can implement it to update its individual content.

That interface is then used by the DatabaseUtilities to do saves/deletes on a single item or to do them in bulk in a single transaction.

Commits

I did some of the development for these changes late at night after a busy week so it is broken into two commits:

No comments :

Post a Comment