vendredi 11 mars 2016

overriding methods of Singleton Sqlite base class

I have a few singleton sqlite adapters for different tables and queries. In those adapters I find there are a few database-initiation methods and variables that could be put in a base class so that I don't need to write them out over and over again in each adapter. The following is the base class I have made so far with the help of this thread :

Base Class DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "postsDatabase";
    private static final int DATABASE_VERSION = 1;
    private static DatabaseHelper sInstance;
    public static String MAIN_TABLE; // will be replaced when instantiated
    private Context context;

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

    public static synchronized DatabaseHelper getInstance(Context context) {
        // Use the application context, which will ensure that you
        // don't accidentally leak an Activity's context.
        // See this article for more information: http://bit.ly/6LRzfx
        if (sInstance == null) {
            sInstance = new DatabaseHelper(context.getApplicationContext());
        }
        sInstance.context = context;
        return sInstance;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion != newVersion) {
            // Simplest implementation is to drop all old tables and recreate them
            db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE);
            onCreate(db);
        }
    }

    // will be replaced when instantiated
    @Override
    public void onCreate(SQLiteDatabase database) {}

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
    }

}

Used in Adapter:

public class AnimalTableAdapter{

    public AnimalTableAdapter(Context context) {

        dbHelper = new DatabaseHelper(context){

            public static final String MAIN_TABLE = "animal";

            @Override
            public void onCreate(SQLiteDatabase db) {
                CREATE_SEARCH_STRING_TABLE = "//****sql query**** //";
                db.execSQL(CREATE_SEARCH_STRING_TABLE);

            }
        };
        db = dbHelper.getWritableDatabase();
    }
}

However, I don't think the DatabaseHelper base class is a singleton because the constructor is public but when I turn it into a private constructor I can no longer override some of the methods and variables like MAIN_TABLE and onCreate in the animal adapter. Can anyone point me the right way to make a singleton base class?

Aucun commentaire:

Enregistrer un commentaire