Q:

When to call findViewById in an Activity

I am encountering the following issue.
I have the following lines of code : 
Spinner domainSpinner = (Spinner) findViewById(R.id.domain);
domainSpinner.setVisibility(View.VISIBLE);

These get executed after the user clicks on menu item in the UI. So I am pretty sure the UI is drawn on the screen. The spinner should be on the screen, and already filled with data.
The menu item is to change the language of the screen. The spinner should than fill up with items in the newly selected language.
In GooglePlay I sometimes get an error report where the stackTrace gives a NullPointerException in the 2nd line. So it must be that domainSpinner is null.
I have never experienced this issue myself. Also we use a beta version of the app for our own use, and none of my collegues has ever had this issue.
I have no idea why the findViewById should sometimes return null. I have tried going back and forward, rotating, .... But I never have this problem.
Note that the item R.id.domain can have a visibility of GONE setted programmatically. But I also played with this but could not reproduce the problem.
Code of the menu item action :
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
   int id = item.getItemId();
   if (id == R.id.action_nl)
   {
      changeLanguage("nl", true);
      return true;
   }
   else if (id == R.id.action_fr)
   {
      changeLanguage("fr", true);
      return true;
   }
   else if (id == R.id.action_en)
   {
      changeLanguage("en", true);
      return true;
   }
   else if (id == R.id.action_de)
   {
      changeLanguage("de", true);
      return true;
   }

   return super.onOptionsItemSelected(item);

}

A:

You should always initialise your views on the OnCreate method in an activity to make sure the view exists when you want to reference it. 
Like below:
private Spinner domainSpinner;

@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        domainSpinner = (Spinner) findViewById(R.id.domain);
    }

Let me know if this helps!
UPDATE: If you need to use the variable outside of the on create method, then declare a global variable and still initialise it on create, then use it where needed.

