Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid findViewById returns null when used in class other than main Activity
    primarykey
    data
    text
    <p>I am trying to get a TextView by ID in my listener class which handles a spinner's onItemSelected event. In my main Activity I can call findViewById(R.id.textView1) and it works fine. But if I call the same function in my spinner listener class it always returns null and forces the app to close.</p> <p>Anyone know why findViewById works in my main Activity but not in my listener class?</p> <p>Here is the code from my main activity. It is called when a button is clicked:</p> <pre><code>public void something () { setContentView(R.layout.spinnerLayout); Spinner spinner = (Spinner) findViewById(R.id.mySpinner); ArrayAdapter&lt;CharSequence&gt; adapter = ArrayAdapter.createFromResource( this, R.array.spinner_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); } </code></pre> <p>And here is the code for MyOnItemSelectedListener:</p> <pre><code>public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int pos, long id) { TextView tv = view.findViewById(R.id.myTextView); // I want to set the text of this text view to the value selected using the spinner tv.setText("Something"); } public void onNothingSelected(AdapterView parent) { // Do nothing. } } </code></pre> <p>What do I need to do to get "TextView tv = view.findViewById(R.id.myTextView);" to work?</p> <p>Thanks!!!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload