使用singleton作为所选数据库值的全局缓存

时间:2011-11-05 08:25:16

标签: android database singleton

我喜欢使用Singleton作为某些数据库值的全局可访问缓存。这是我对带有样本变量gi1和gDBAdapter的单例的定义:

public class GlobalVars {
    private Integer gi1;
    private WebiDBAdapter gDBAdapter;

    private static GlobalVars instance = null;
       protected GlobalVars() {
          // Exists only to defeat instantiation.
       }
       public static GlobalVars getInstance() {
          if(instance == null) {
             instance = new GlobalVars();
          }

          //  now get the current data from the DB, 

          WebiDBAdapter myDBAdapter = new WebiDBAdapter(this);  // <- cannot use this in static context

          gDBAdapter = myDBAdapter;     // <- cannot use this in static context
          myDBAdapter.open();

          Cursor cursor = myDBAdapter.fetchMainEntry();
          startManagingCursor(cursor); // <- the method startManagingCursor is undefined for the type GlobalVars
          // if there is no DB yet, lets just create one with default data
            if (cursor.getCount() == 0) {
                cursor.close();
                createData();  // <- the method createData is undefined for the type GlobalVars
                cursor = myDBAdapter.fetchMainEntry();
                startManagingCursor(cursor);// <- the method startManagingCursor is undefined for the type GlobalVars
            }

            gi1 = cursor.getInt(cursor  // <- Cannot make a static reference to the non-static field gi1
                    .getColumnIndexOrThrow(WebiDBAdapter.KEY1));
            if (gi1 == null) gi1 = 0;

            cursor.close();

          return instance;
       }

但是无法识别对实例变量的所有引用。

所有// <-条目都显示我得到的错误

我想有一些基础知识我不在这里。

使用数据库中的值创建单例并初始化其值的正确方法是什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用Application

静态函数

中也没有this这样的东西