Search code examples
androidfindviewbyid

android: findViewById returns NULL when accesses from another class


I have a MainActivity.class on which I do setContentView, here are the three variables I used to

    EditText labelText = (EditText) findViewById(R.id.label_field);
    EditText phoneText = (EditText) findViewById(R.id.phone_field);
    Spinner deviceTypeSpinner = (Spinner) findViewById(R.id.device_type_spinner);
    Button registerButton = (Button) findViewById(R.id.register_button)

Now, I have a separate class which extends an async task, I am trying to modify the above fields from the async task(class located in another file).

In order to do this, I am passing the context of the activity to async task and doing the steps below

            MainActivity activity = (MainActivity)context;
            Button buttonRegister =(Button)activity.findViewById(R.id.register_button);
            EditText labelText = (EditText)activity.findViewById(R.id.label_field);

            buttonRegister.setEnabled(true);
            labelText.setFocusable(true);

but the buttonRegister returns null and the app crashes, can anybody tell me where have I gone wrong,

  java.lang.NullPointerException
    at        com.yantranet.minixagent.requests.DeviceCreateRequest$1.onClick(DeviceCreateRequest.java:237)
    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4895)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
    at dalvik.system.NativeStart.main(Native Method)

Solution

  • but the buttonRegister returns null and the app crashes, can anybody tell me where have I gone wrong,

    i don't see where you are calling

    setContentView(<layout>);
    

    method. Without it, it always returns NPE because this method cares about inicialisation of all UI instances in specified layout. You have to call it always before you want to initialise widgets with

    findViewById(<id>);
    

    Since you are calling it in another class it won't work (class know nothing about what you did in other class). You need to:

    • pass widgets via some constructor
    • change application logic (most likely is not designated correctly)