Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a database-intensive app. Almost every activity requires access to the database, both reading and writing. I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediately before and after use.

So I opted to use a single instance of the database. Now I have no problems--but is this right?

Application class

public class ApplicationClass extends Application
    private DatabaseAdapter PrDatabaseAdapter; 

    public DatabaseAdapter getDatabaseAdapter()
        return PrDatabaseAdapter;

    public void onCreate()

        PrDatabaseAdapter = new DatabaseAdapter(this);

Adapter Class The database adapter just sits on top of the DatabaseManager (my SQLiteOpenHelper)

private Context context;
private SQLiteDatabase db;
private DatabaseManager dbManager;

 * The DatabaseAdapter contains all interaction logic for the database
 * @param context
public DatabaseAdapter(Context context)
    this.context = context;

 * Opens writable database
 * @return DatabaseAdapter;
 * @throws SQLiteException
public DatabaseAdapter open() throws SQLiteException
    dbManager = new DatabaseManager(context);
    db = dbManager.getWritableDatabase();
    return this;

 * Closes database connection
public void close()

I'm still learning a lot about Java and Android and I would appreciate some insight to the pros and cons of this approach.

share|improve this question

1 Answer 1

I'm not familiar with Android, so just some generic Java notes:

  1. PrDatabaseAdapter should be prDatabaseAdapter (with lowercase first letter). See Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions and The Java Language Specification, Java SE 7 Edition, 6.1 Declarations:

    Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized.

  2. Javadoc comments like @param context aren't too useful, they say nothing more than the source code alone. I'd remove them.

  3. Does it make sense to create a DatabaseAdapter with null context? I'd check this in the constructor and throw and NullPointerException if it's null. See Effective Java, 2nd edition, Item 38: Check parameters for validity

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.