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 -
super
on
the top in constructor) 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 -
getDefaultSharedPreferences
?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.
move getDBLocation
code into a static method:
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);
}