Android SQLiteOpenHelper错误-对super的调用必须是构造函数中的第一条语句
让我首先说,在问这个问题之前,我已经读过很多类似的问题,但我找不到任何可能的解决方案 我试图扩展Android SQLiteOpenHelper错误-对super的调用必须是构造函数中的第一条语句,android,constructor,android-sqlite,super,sqliteopenhelper,Android,Constructor,Android Sqlite,Super,Sqliteopenhelper,让我首先说,在问这个问题之前,我已经读过很多类似的问题,但我找不到任何可能的解决方案 我试图扩展SQLiteOpenHelper类,但有两个显著的区别- 我正在使用SQLCipher(如果我在 顶部(在构造函数中) 我正在从中获取数据库位置 SharedReferences(这就是为什么,我必须将其放在super之前) 例如,以下构造函数工作正常(我排除了与我的问题无关的导入和函数)- 但是,在我的例子中,我想允许数据库位置是可变的(例如,用户可以从下载文件夹使用它,或者如果用户不允许使用外部存
SQLiteOpenHelper
类,但有两个显著的区别-
getExternalFilesDir()
)->因此,长话短说,我正在共享首选项中保存数据库位置,并尝试通过如下修改构造函数来使用它-
public QuestionBankDBHelper(Context context) {
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(NoContextAvailable); //What should I use here for the context ?
String getDBLocation = getPrefs.getString("MY_DATABASE_LOCATION", Environment.getExternalStorageDirectory().toString()+File.separator + "myFolder"
+ "/" + DB_LOCAL_NAME);
super(context, getDBLocation, null, 1);
this.myContext = context;
SQLiteDatabase.loadLibs(context);
}
显然,上面修改的构造函数不起作用,并给出以下两个错误-
GetDefaultSharedReferences
一起使用即使经过大量的试验和搜索,我也不知道如何解决这两个问题,并将我的数据库位置作为变量。将
getDBLocation
代码转换为静态方法:
private static String getDBLocation(Context context) {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String getDBLocation = getPrefs.getString("MY_DATABASE_LOCATION",
Environment.getExternalStorageDirectory().toString()
+ File.separator + "myFolder" + "/" + DB_LOCAL_NAME);
return getDBLocation;
}
public QuestionBankDBHelper(Context context) {
super(context, getDBLocation(context), null, 1);
this.myContext = context;
SQLiteDatabase.loadLibs(context);
}
将
getDBLocation
代码移到静态方法中:
private static String getDBLocation(Context context) {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String getDBLocation = getPrefs.getString("MY_DATABASE_LOCATION",
Environment.getExternalStorageDirectory().toString()
+ File.separator + "myFolder" + "/" + DB_LOCAL_NAME);
return getDBLocation;
}
public QuestionBankDBHelper(Context context) {
super(context, getDBLocation(context), null, 1);
this.myContext = context;
SQLiteDatabase.loadLibs(context);
}
简单回答:
super
作为第一条语句,并使用静态函数return作为路径参数super
作为第一条语句,并使用静态函数return作为路径参数正确的解决方案是删除有关在此类中查找数据库路径的任何知识。在构造此类之前,您应该进行所有检查、计算和提问,并且只调用具有定义路径的此类构造函数。什么应该是
GetDefaultSharedReferences
的上下文,我似乎不能在静态函数中使用,myContext
。@OlegKhalidov感谢更新的答案,我现在正在测试它,我会很快给你回复的。@OlegKhalidov成功了,谢谢。我想你忘了添加return getDBLocation
在静态方法中,GetDefaultSharedReferences
的上下文应该是什么,我似乎不能在静态函数中使用,myContext
。@OlegKhalidov感谢更新的答案,我现在正在测试,很快会给你回复。@OlegKhalidov它成功了,谢谢。我想你忘了添加return getDBLocation静态方法中的代码>