-1

When I cast my elements from the other layout I got this error.

final  Spinner mainIng = (Spinner) findViewById(R.id.spinner);
final  EditText sub1 = (EditText) findViewById(R.id.sub1);
final  EditText sub2 = (EditText) findViewById(R.id.sub2);
final  EditText sub3 = (EditText) findViewById(R.id.sub3);
final  EditText sub4 = (EditText) findViewById(R.id.sub4);
final  EditText sub5 = (EditText) findViewById(R.id.sub5);
final  EditText sub6 = (EditText) findViewById(R.id.sub6);

heres my error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
  • are you running this inside an `Activity`? – giannisf Mar 01 '16 at 16:09
  • No it is located before my Activity was called. I want it to be a global variable. – Jellolicious Mar 01 '16 at 16:10
  • There is a good amount of code missing from this snippet to answer the question accurately. Can you please post the entire class and method declaration if it's not too large. At least the whole method and which class it is contained in would be helpful. – Bobbake4 Mar 01 '16 at 16:14
  • Share your XML code as well and also tell if you are placing above mentioned code after setContentView ? – Salman Nazir Mar 01 '16 at 16:19

3 Answers3

1

Are you calling this from onCreate()? If yes try moving it to onCreateView() and call it with the inflated view or call it even later.

If you do then findViewById won't work, because the window is not yet created.

findViewById() returns null when I call it in onCreate()

Community
  • 1
  • 1
Jan
  • 1,504
  • 10
  • 15
0

You need to init views in onCreate():

public class YourActivity extends Activity {
Spinner mainIng; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_xml);
    mainIng= (Spinner) findViewById(R.id.spinner);
}
CaptJak
  • 3,592
  • 1
  • 29
  • 50
Leonid Veremchuk
  • 1,952
  • 15
  • 27
0

Place your code after the setContentView in your activity.

if you want them to be available in every method of your activity, declare them as fields.

public class MyActivity extends Activity {
         Spinner mySpiner;


     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

       mySpiner = (Spinner) findViewById(R.id.mySpiner);

and then instantiate them after.

giannisf
  • 2,479
  • 1
  • 17
  • 29