How to transfer the database adapter to another event?

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

The "main action" of my application provides a button. If the user clicks on this button, a search dialog is called up. The search itself is performed in the async task, as it may take some time. So far so good.

The main action also creates a database adapter object, which is used to initialize the database, execute queries, etc. But how can I use this adapter object in a search operation?

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

Search activity

  • Get Intent and Get Request from Search Dialog -> OK
  • How can I use the database adapter again to execute a query?

? - , [...]?

,

+3
3

DatabaseAdapter . :

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;

}

:

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

    return sWritableAdapter;

}

, , , :

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

Marco

+3

Application . , .

public class ApplicationClass extends Application {

    Adapter adapter.

    @Override 
    public void onCreate(){
    adapter=new Adapter();
        super.onCreate();
    }

    public Adapter getAdapter(){
        return adapter;
    }

}

Activity:

Adapter adapter=(ApplicationClass)getApplication().getAdapter();

- . ApplicationClass - . , MyAppNameApplication. , AndroidManifest.xml

+8

You better implement ContentProvider

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

They are single point and are available from (almost) everywhere in your application.

0
source

All Articles