Akash D G Akash D G - 6 months ago 38
Java Question

findViewById not working in static function

I found error in

in static function.

my function is--

public static void onYearSelect() {

Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();


is there any way to solve this error!

can i store value of Spinner in yearName as String


You need to add view inside function as parameter.

public static void onYearSelect(View view) {

    Spinner yearSelector;
    yearSelector = (Spinner) view.findViewById(R.id.year_submit);
    yearName = yearSelector.getSelectedItem().toString();


The view which contains your layout data.

When you call that function add onYearSelect(rootView) here rootView have the layout view.


What is View here ?

A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.

You can read more here.