Akash D G
Akash D G

Reputation: 188

findViewById not working in static function

I found error in findViewById 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

Upvotes: 1

Views: 1984

Answers (2)

Jay Rathod
Jay Rathod

Reputation: 11245

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.

EDIT 1:

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.

Upvotes: 4

Amit Yadav
Amit Yadav

Reputation: 406

Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,

yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
 String yearName = parentView.getItemAtPosition(position).toString()
}

@Override
public void onNothingSelected(AdapterView<?> parentView) {
    // your code here
}});

Upvotes: 0

Related Questions