How to pass database adapter to another activity?

孤人 提交于 2019-12-23 22:45:32

问题


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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!