androidandroid-sqliteandroid-sharedpreferences

Using SharedPreferences with SQLiteOpenHelper before initialising the database


I would like to have a database for each user of my app. Usernames are stored in SharedPreferences. So I'm looking for something like this:

public class DatabaseHelper extends SQLiteOpenHelper {

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    String LoggedInUser = sp.getString("user","");

    public static final String DATABASE_NAME = LoggedInUser + ".db";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    public void onCreate(SQLiteDatabase db) {
        ...
    }
    ...

}

But this doesn't work, because SharedPreferences need context (using getApplicationContext() instead of this doesn't work either. This can be solved by something like this:

private Context appContext;
public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    this.appContext = context;
}

And then accessing SharedPreferences afterwards.

But I need to access SharedPreferences before this method ("DATABASE_NAME" is used in the above method and I want to define "DATABASE_NAME" using SharedPreferences).

Is there any way for doing this?


Solution

  • Since call to super() must be first statement, the only solution to achieve it would be to pass the DATABASE_NAME as constructor parameter:

    public DatabaseHelper(final Context context, final string dbName) {
            super(context, dbName, null, 1);
     }
    

    You can then either implement factory or Facade pattern to construct or pass the value to DatabaseHelper or simply pass the dbName value from Activity/Fragment.

    An example of Factory could be:

    public final class DatabaseFactory {
    
        public static DatabaseHelper getDataBaseHelper(final Context context){
            final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            final String loggedInUser = sp.getString("user","");
            return new DatabaseHelper(context,loggedInUser);
        }
    }
    

    In Activity you can access the Helper as follows:

    public class MainActivity extends Activity{
        ...
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            ...
            final DatabaseHelper myDB = DatabaseFactory.getDataBaseHelper(this);
            ...
        }
    }