2

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!

user387184
  • 10,953
  • 12
  • 77
  • 147

1 Answers1

2

Use the Application class,

also there is no such thing as this in a static function

Community
  • 1
  • 1
Reno
  • 33,594
  • 11
  • 89
  • 102
  • The problem with the application class is - as I read - I cannot rely on its values to exist throughout the livecycle of the app. I read that it might get killed when the app gets interrupted by a phone call and loose its values when it returns. Isn't this true? – user387184 Nov 05 '11 at 09:17
  • 1
    I think the activity may be restarted, but the application context is not lost. [Read this if you want to store activity related info.](http://developer.android.com/guide/topics/resources/runtime-changes.html). If at all you found that phone calls are disrupting your data, use the `PhoneStateListener` to detect them and handle it . The OS will only kill your application if there is a memory shortage during the phone call – Reno Nov 05 '11 at 09:27