Skip to content Skip to sidebar Skip to footer

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);

Solution 1:

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;

@OverrideprotectedvoidonCreate(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.

Solution 2:

You can try this. Make sure the domainSpinner is initialized on the Main Thread. Also add a condition for setting visibility only when domainSpinner is not equal to null.

HandlermainHandler=newHandler(context.getMainLooper());
mainHandler.post(newRunnable() {

    @Overridepublicvoidrun() {
        SpinnerdomainSpinner= (Spinner) findViewById(R.id.domain);
        if(domainSpinner!=null) {
           domainSpinner.setVisibility(View.VISIBLE);
        }
    }
});

Post a Comment for "When To Call Findviewbyid In An Activity"