开发者

How to pass database adapter to another activity?

开发者 https://www.devze.com 2023-03-05 10:10 出处:网络
I\'m having some trouble unders开发者_运维知识库tanding the search dialog in the Android SDK.

I'm having some trouble unders开发者_运维知识库tanding 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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消