Skip to content Skip to sidebar Skip to footer

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 dialo

Solution 1:

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

privatestaticDatabaseAdaptersWritableAdapter=null;
privatestaticDatabaseAdaptersReadableAdapter=null;

publicstatic DatabaseAdapter openForReading(Context ctx) {
    if(sReadableAdapter == null)
    sReadableAdapter = newDatabaseAdapter(newDatabaseHelper(ctx).getReadableDatabase());

    return sReadableAdapter;

}

or for write access:

publicstaticDatabaseAdapteropenForWriting(Context ctx) {
if(sWritableAdapter == null)
        sWritableAdapter = newDatabaseAdapter(newDatabaseHelper(ctx).getWritableDatabase());

    return sWritableAdapter;

}

So in your searchable activity you would write for instance:

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

Marco

Solution 2:

You should rather implement an ContentProvider

http://developer.android.com/guide/topics/providers/content-providers.html

They are singletons, and accessible from (almost) everywhere in your application.

Post a Comment for "How To Pass Database Adapter To Another Activity?"