I like to use a Singleton as a globally accessible cache for certain database values. This is my definition of the singleton with sample variables gi1, and gDBAdapter:
public class GlobalVars {
private Integer gi1;
private WebiDBAdapter gDBAdapter;
private static GlobalVars instance = null;
protected GlobalVars() {
// Exists only to defeat instantiation.
}
public static GlobalVars getInstance() {
if(instance == null) {
instance = new GlobalVars();
}
// now get the current data from the DB,
WebiDBAdapter myDBAdapter = new WebiDBAdapter(this); // <- cannot use this in static context
gDBAdapter = myDBAdapter; // <- cannot use this in static context
myDBAdapter.open();
Cursor cursor = myDBAdapter.fetchMainEntry();
startManagingCursor(cursor); // <- the method startManagingCursor is undefined for the type GlobalVars
// if there is no DB yet, lets just create one with default data
if (cursor.getCount() == 0) {
cursor.close();
createData(); // <- the method createData is undefined for the type GlobalVars
cursor = myDBAdapter.fetchMainEntry();
startManagingCursor(cursor);// <- the method startManagingCursor is undefined for the type GlobalVars
}
gi1 = cursor.getInt(cursor // <- Cannot make a static reference to the non-static field gi1
.getColumnIndexOrThrow(WebiDBAdapter.KEY1));
if (gi1 == null) gi1 = 0;
cursor.close();
return instance;
}
But all the references to the instance vars are not recognized.
All the // <-
entries show the errors I get
I guess there is some basics that I am not doing right here.
What would be the right way to create the singleton and initialize its values with the values from the database?
Thanks for your help!