问题
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
- Get intent and receive query from search dialog -> OK
- 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
回答1:
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
回答2:
You can create adapter in Application class, and retreieve it in all your activities. That's what I do for my projects.
public class ApplicationClass extends Application {
Adapter adapter.
@Override
public void onCreate(){
adapter=new Adapter();
super.onCreate();
}
public Adapter getAdapter(){
return adapter;
}
}
Then call from Activity:
Adapter adapter=(ApplicationClass)getApplication().getAdapter();
Something like that. ApplicationClass is for your app name. Could be MyAppNameApplication You should create it in your package and then declare in AndroidManifest.xml
回答3:
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.
来源:https://stackoverflow.com/questions/5956196/how-to-pass-database-adapter-to-another-activity