Search code examples
androidinitializationglobal-variablesfinal

How to make a final global variable in Android


I searched but didn't found an answer. How can I make a variable final and global. I already tried this:

public class StartActivity extends Activity {
    ...
    private final Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    ...
}

But i got this error:

06-07 19:57:38.461: E/AndroidRuntime(13810): java.lang.RuntimeException:
Unable to instantiate activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.
StartActivity}: java.lang.IllegalStateException: System services not available to
Activities before onCreate()

I don't know how to avoid this error, because when I tried this:

public class StartActivity extends Activity {
    ...
    private final Dialog dialog;
    ...
}

and initialize the variable in the onCreate() method, I get this error in Eclipse:

The blank final field dialog may not have been initialized.

Solution

  • Remove the final modifier

    public class StartActivity extends Activity {
    
    private Dialog dialog; // declare it as a instance variable
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    { 
          super.onCreate(savedInstanceState);
          setContentView(R.layout.yourlayout);
          dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
          // initialize dialog
    }  
    

    Now you can use the dialog in onClick.

    Also note this refers to Activity Context and context is available once activity is created.