开发者

Store shared object for all activities

I have a class:

public class DbAdapter {
    private DbHelper dbHelper;
    private SQLiteDatabase db;
    private final Context context;
    ...
}

and i want have it available in all activities. The class prov开发者_JAVA百科ides access to my sqlite database.

What is the most elegant and neat way to do it? I thought about creating object in each activity (it should "connect" me to the same database, right?).


You can achieve it extending the Application class. Google has this to say about it:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

I have done it myself like this:

public class App extends Application {

    private DbHelper dbHelper;

    @Override
    public void onCreate() {
        super.onCreate(); 
        dbHelper = new DbHelper(this);

    }

    public SQLiteDatabase getDatabase(){
        return dbHelper.getWritableDatabase();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        dbHelper.close();
    }   
}

Then you just access it calling getApplicationContext.getDatabase()


You may take a look at the Singleton Pattern, it gives the opportunity to make a class have only one object created and to make this object accessible from everywhere. Hope this helps.


I think the best way to implement this is to use Service. The Service will keep reference to DbAdapter and all your activities will connect to the Service. When activity is connected to the service it'll keep the reference to it and every time it needs db access it'll use to get the DbAdapter. Using this approach you'll have control over your db connection. If no activities are connected to the service than no one is using the db connection and you can free it.


Have a look at ContentProviders. They're made for accessing data. And regardless of all the emphasis on "sharing data between applications" in the link, they don't have to be public - you can use them as a centralized way to access data in your app.

This blog entry on 'Writing Your Own ContentProvider' shows some code for setting up a ContentProvider that works within one application.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜