对SQLiteDatabase使用Singleton设计模式 [英] Using Singleton design pattern for SQLiteDatabase

查看:183
本文介绍了对SQLiteDatabase使用Singleton设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android上的新手,并且我正在研究一个简单的应用程序,以获得一些基本的经验.我的应用程序非常简单,包括广播接收器和一些活动.这两个组件都使用一个数据库,因此从理论上讲,这两个组件都可能尝试同时访问数据库.

I'm rather newbie on Android, and I'm working on a simple application to get some basic experience. My app is pretty simple and consists among other things of a broadcast receiver and some activities. Both components make use of a single database, so in theory it could happen that both try to access the db concurrently.

目前,我只是在每次需要时实例化db对象(这是一个SQLite db helper类),并执行所需的操作:查询,插入等.

Currently I'm simply instantiating the db object (which is-a SQLite db helper class) each time I need it, and performing the needed operations: query, insert, etc.

从我在这里和其他一些文档中所读的内容来看,如果并发访问数据库,则会出现数据库锁定"异常的问题,因此更好的方法是使用该数据库的单个实例对象,以便所有组件始终使用相同的数据库连接.

From what I've been reading here and in some other documents, this has the problem of getting a "db locked" exception in case the db is accessed concurrently, so a better approach would be having a single instance of this db object so all components use the same db connection at all times.

以上推理正确吗?那么单身人士将是一个足够好的解决方案吗?我知道有些纯粹主义者可能会反对它,但是请注意,这是一个相当简单的应用程序,因此我可以负担其他情况下无法做到的事情.

Is the above reasoning correct? Would a singleton then be a good-enough solution for this? I know some purists may argue against it, but please note that this is a rather simple application so I can afford doing things I wouldn't in other cases.

否则,更好的选择是什么?我已经读过有关使用内容提供程序的信息,但是这样做除了我不想与其他活动共享数据外,对它来说已经太多了.我确实已经阅读了此 发布 并发现它很有帮助.

Otherwise, what would a better option be? I've read about using content provider but it would be too much for this, besides that I'm not interested to share the data with other activities. I have indeed read this post and found it rather helpful.

推荐答案

点击在这里可以看到我有关此主题的博客文章.


以下是一些示例代码,它们说明了三种可能的方法.这些将允许访问整个应用程序中的数据库.

Click here to see my blog post on this subject.


Here is some sample code that illustrates three possible approaches. These will allow access to the database throughout the application.

这不是完整的实现,但是它应该为您提供一个如何正确设计DatabaseHelper类的好主意.静态工厂方法可确保在任何时候仅存在一个DatabaseHelper实例.

This isn't the complete implementation, but it should give you a good idea on how to go about designing the DatabaseHelper class correctly. The static factory method ensures that there exists only one DatabaseHelper instance at any time.

/**
 * create custom DatabaseHelper class that extends SQLiteOpenHelper
 */
public class DatabaseHelper extends SQLiteOpenHelper { 
    private static DatabaseHelper mInstance = null;

    private static final String DATABASE_NAME = "databaseName";
    private static final String DATABASE_TABLE = "tableName";
    private static final int DATABASE_VERSION = 1;

    private Context mCxt;

    public static DatabaseHelper getInstance(Context ctx) {
        /** 
         * use the application context as suggested by CommonsWare.
         * this will ensure that you dont accidentally leak an Activitys
         * context (see this article for more information: 
         * http://android-developers.blogspot.nl/2009/01/avoiding-memory-leaks.html)
         */
        if (mInstance == null) {
            mInstance = new DatabaseHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

    /**
     * constructor should be private to prevent direct instantiation.
     * make call to static factory method "getInstance()" instead.
     */
    private DatabaseHelper(Context ctx) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.mCtx = ctx;
    }
}

方法2:使用ContentProvider提取SQLite数据库

这是我建议的方法.例如,新的CursorLoader类需要ContentProvider,因此,如果您希望Activity或Fragment用CursorLoader实现LoaderManager.LoaderCallbacks<Cursor>(我建议您利用它,这很神奇!),将需要为您的应用程序实现ContentProvider.此外,您不必担心使用ContentProviders创建Singleton数据库帮助器.只需从Activity中调用getContentResolver(),系统就会为您处理所有事情(换句话说,无需设计Singleton模式来防止创建多个实例).

Approach #2: abstract the SQLite database with a `ContentProvider`

This is the approach I would suggest. For one, the new CursorLoader class requires ContentProviders, so if you want an Activity or Fragment to implement LoaderManager.LoaderCallbacks<Cursor> with a CursorLoader (which I suggest you take advantage of, it is magical!), you'll need to implement a ContentProvider for your application. Further, you don't need to worry about making a Singleton database helper with ContentProviders. Simply call getContentResolver() from the Activity and the system will take care of everything for you (in other words, there is no need for designing a Singleton pattern to prevent multiple instances from being created).

希望这会有所帮助!

这篇关于对SQLiteDatabase使用Singleton设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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