开发者

Using singleton class for sharing instance of database between activities?

Hey! I want to use a singleton class, because if I open the database every activity I get "Leak found"( that happens because I open the database even if it is already open ) . I create a singleton class , but I don't know how should I use it.

Here is my class:

package com.ShoppingList;

import com.Shopp开发者_如何学GoingList.databases.DbAdapter;

public class DbManager {

    DbAdapter db;

    // singleton
    private static DbManager instance = null;

    private DbManager() {

    }

    public static DbManager getInstance() {
        if (instance == null)
            instance = new DbManager();
        return instance;
    }

    public void setinstance(DbAdapter db){
        this.db=db;
    }

    public DbAdapter getinstancedb(){
        return db;
    }
}

In the first activity I put :

db = new DbAdapter(this);
        db.open();
        DbManager.getInstance().setinstance(db);

and for the next activity : DbManager.getInstance().getinstancedb(); but I get force close for second activity.

Can anyone help me how to use it? Thanks...


You can extend Application class and create there an instance of DbAdapter. This way it will be shared by all your activities.


Because db has the same context and life cycle of your first activity. Make your methods public and make them do all the setup/teardown necessary to return your desired result.


regarding the leak warning. Are you closing your db manager connection in onDestroy()?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜