Android Room-避免将上下文传递给Singleton [英] Android Room - Avoid passing Context into Singleton

查看:155
本文介绍了Android Room-避免将上下文传递给Singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将项目迁移到Android Room.阅读Android Room文档后,我发现Singleton适合访问我的数据库.

I am trying to migrate a project to Android Room. After reading the Android Room documentation I noticed that a Singleton is suitable for accessing my database.

来自Android开发人员的语录:

Quote from Android Developer:

注意:如果您的应用程序在单个进程中运行,则在实例化AppDatabase对象时应遵循单例设计模式.每个RoomDatabase实例都非常昂贵,并且您几乎不需要在单个进程中访问多个实例.

Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.

我编写了以下代码:

@Database(entities = {Category.class, News.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static final String DB_NAME = "database.db";
    private static AppDatabase instance;

    public abstract CategoryDao categoryDao();
    public abstract NewsDao newsDao();

    private AppDatabase () {}

    public static AppDatabase getInstance(Context context) {
        if (instance == null) {
            synchronized (AppDatabase.class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, DB_NAME).build();
                }
            }
        }
        return instance;
    }
}

一个简单的双重检查锁定Singleton.

Just a simple double checking locking Singleton.

我已经阅读了一些指南/教程,几乎每个人都采用了类似的方法,但是我发现这种方法存在一些问题:

I have read some guides/tutorials and almost everyone comes with a similar approach, however I can see some problems with this approach:

  • 需要每次都传递Context,即使只需要一次就可以初始化Singleton.
  • 如果我需要在没有Context可用的情况下访问数据库怎么办?
  • 甚至可以将参数发送给Singleton吗?
  • Need to pass a Context every single time, even only you need it one time to initialize the Singleton.
  • What if I need to access the database without a Context available?
  • It's even admissible to send parameters to a Singleton?

有什么想法可以实现解决这些问题的Room Database Singleton吗?

如果可能,我想避免使用像Dagger2这样的DI库.

I would like to avoid DI libraries like Dagger2 if possible.

推荐答案

您可以初始化数据库,并将其实例保存到Application类中.

You can initialize your database and save an instance of it into your Application class something like this.

public class MyApplication extends Application {

    public AppDatabase database;

    @Override
    public void onCreate() {
        super.onCreate();

        database = AppDatabase.getInstance(this)
    }
}

您可以像

((MyApplication)activity).dabase

希望这会有所帮助.

这篇关于Android Room-避免将上下文传递给Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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