Мне нравится использовать Singleton как глобально доступный кеш для определенных значений базы данных. Это моё определение синглтона с примерами переменных gi1 и 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;
}
Но все ссылки на экземпляры не распознаются.
Все записи // <-
показывают ошибки, которые я получаю
Полагаю, есть некоторые основы, которые я здесь не делаю.
Каков будет правильный способ создания синглтона и инициализации его значений значениями из базы данных?
Спасибо за вашу помощь!