Let me start by saying that before asking this question, I have already read many similar questions, but I couldn't find any possible solution for my situation.
I am trying to extend SQLiteOpenHelper
class, but with 2 significant differences -
- I am using SQLCipher (using it doesn't bother, if I use
super
on the top in constructor) - I am getting my database location from SharedPreferences (this is why, I have to put it before super)
For e.g., following constructor works fine (I have excluded the imports and functions which are not relevant to my question)-
import net.sqlcipher.Cursor;
import net.sqlcipher.SQLException;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;
public class LocalDBHelper extends SQLiteOpenHelper {
public static String DB_LOCAL_NAME = "localdata.db";
public static SQLiteDatabase myDataBase;
private final Context myContext;
public LocalDBHelper(Context context) {
super(context, Environment.getExternalStorageDirectory().toString()+File.separator + "myFolder"
+ "/" + DB_LOCAL_NAME, null, 1);
this.myContext = context;
SQLiteDatabase.loadLibs(context);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
onCreate(db);
}
}
But, in my case, I want to allow the database location to be variable (e.g. user can use it from Downloads folder or if user does not give permission to use external storage(as in case of Android 6.0), then use internal storage or use getExternalFilesDir()
depending upon the situation) -> So, long thing short, I am saving database location in Shared Preferences, and tried to use it by modifying the constructor as following -
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);
}
Obviously the above modified constructor doesn't work, and gives following two errors -
- What Context can be used with
getDefaultSharedPreferences
? - Call to super must be the first statement in Constructor.
Even after a lot of trials and search, I couldn't figure how to work around these two problems, and have my database location as variable.