使用单类活动之间共享数据库实例? [英] Using singleton class for sharing instance of database between activities?

查看:213
本文介绍了使用单类活动之间共享数据库实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿!我想用一个单独的类,因为如果我打开数据库的每一次活动,我得到泄漏发现(这种情况发生,因为我打开,即使它已经打开数据库)。我创建了一个单独的类,但我不知道我应该如何使用它。

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.

下面是我的类:

package com.ShoppingList;

import com.ShoppingList.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;
    }
}

在第一个活动,我把:

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

和为下一个活动:DbManager.getInstance()getinstancedb();但我得到强制关闭的第二个活动。

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...

推荐答案

您可以扩展的 应用 类并创建有 DbAdapter 。这样,它会被所有的活动进行共享。

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

这篇关于使用单类活动之间共享数据库实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆