Search code examples
androiddatabasesearchable

How to pass database adapter to another activity?


I'm having some trouble understanding the search dialog in the Android SDK.

The "main activity" of my application provides a button. If the user clicks this button the search dialog is called. The search itself is then done in an async task as it might need some time. So far so good.

The main activity also creates a database adapter object which is used to initialize the database, perform queries, etc. But how can I use this adapter object in the searchable activity?

MAIN activity
// Init database
DatabaseAdapter dba = new DatabaseAdapter();
dba.init();
// open search dialog
if (buttonClick) onSearchRequest();

Searchable activity

  1. Get intent and receive query from search dialog -> OK
  2. How can I use the database adapter again to perform a query?

Do I have to create a new object? Can I pass it somehow from the min activity to the searchable activity, [...]?

Thanks,
Robert


Solution

  • An option would be to use a singleton and provide access to the DatabaseAdapter via a static method. Ex:

    private static DatabaseAdapter sWritableAdapter = null;
    private static DatabaseAdapter sReadableAdapter = null;
    
    public static DatabaseAdapter openForReading(Context ctx) {
        if(sReadableAdapter == null)
        sReadableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getReadableDatabase());
    
        return sReadableAdapter;
    
    }
    

    or for write access:

    public static DatabaseAdapter openForWriting(Context ctx) {
    if(sWritableAdapter == null)
            sWritableAdapter = new DatabaseAdapter(new DatabaseHelper(ctx).getWritableDatabase());
    
        return sWritableAdapter;
    
    }
    

    So in your searchable activity you would write for instance:

    DatabaseAdapter adapter = DatabaseAdapter.openForReading(ctx);
    adapter.searchSomething();
    

    Marco