2014-02-26 127 views
1

我试图让我的SQLite数据库在我使用单例模式Android应用程序全局访问:Android的全球访问SQLite数据库

public class MySQLiteOpenHelper extends SQLiteOpenHelper { 
    private static final String DATABASE_NAME = "foo"; 
    private static final int DATABASE_VERSION = 1; 
    private static MySQLiteOpenHelper instance; 

    private MySQLiteOpenHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    public static MySQLiteOpenHelper getInstance(Context context) { 
     if (instance == null) { 
      instance = new MySQLiteOpenHelper(context); 
     } 
     return instance; 
    } 

    public static MySQLiteOpenHelper getInstance() throws UnsupportedOperationException { 
     if (instance == null) { 
      throw new UnsupportedOperationException(); 
     } 
     return instance; 
    } 

... 

这里的想法是,首先调用的是getInstance(Context context)通过在应用程序对象。此后,我可以使用getInstance(),因为我无法获得Context对象的句柄。

不过,我来脱胶当我做出初步MySQLiteOpenHelper.getInstance(getApplication())电话:

java.lang.IllegalStateException: getDatabase called recursively 
     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:204) 
     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164) 

任何人都可以摆脱对这里发生了什么任何灯光或暗示对实现我的目标更好的技术?

干杯!

+0

只是创建'SQLiteOpenHelper'不会导致这种情况。发布你的助手'onCreate()'代码,你可能在那里有'getWritableDatabase()'。 – laalto

+0

嘎!我以为我没有在'onCreate()'方法中犯下任何罪行,但我确实在那里调皮捣蛋!我会爬回我的岩石下... 谢谢! – user3352488

回答

2

您发布的代码就好了。

java.lang.IllegalStateException: getDatabase called recursively 

这是您拨打电话时引起的,例如, getWritableDatabase()递归。它

一个常见原因是调用getWritableDatabase()数据库帮手onCreate()。当getWritableDatabase()被调用且数据库不存在时,调用onCreate()。再次调用getWritableDatabase()是一个错误。您应该使用传递给onCreate()的可写SQLiteDatabase作为参数。

0

你MySQLiteOpenHelper应该工作正常。

这个类是没有问题的。