简体   繁体   中英

NullPointerException over accessing resource when calling the method from extended class

I have an activity class ClassA extended from ListActivity which has few function that manipulate the UI.

I have another class ClassB extended from ClassA which handles map related logics. The ClassB calls a function updateNearByNames of ClassA .

But when the function reaches the line where it needs to access a UI resource findViewById(R.id.namesAround); it throws a NullPointerException .

The UI resource exists and the function works fine if called from within ClassA .

08-09 22:43:22.705: E/AndroidRuntime(5593): FATAL EXCEPTION: main
08-09 22:43:22.705: E/AndroidRuntime(5593): java.lang.NullPointerException
08-09 22:43:22.705: E/AndroidRuntime(5593):     at android.app.Activity.findViewById(Activity.java:1839)

Code:

public class ClassA extends ListActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        setContentView(R.layout.main_v);
        ...

    }
    public void updateNearByNames() {
        Spinner reportEventNamesAroundSpinner = (Spinner) findViewById(R.id.namesAround); // Error Here
        ...
        ...
    }
}


public class ClassB extends ClassA implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, OnItemSelectedListener {
    ...    
    @Override
    public void onConnected(Bundle connectionHint) {
            updateNearByNames();
    }
}

it won't work this way. You can't access the Views of an Activity by just subclassing it, you will always get an NPE . What you need to do is adding a constructor to your second class and pass an instance of your Activity .

  public ClassB(ClassA a){
   this.a = a;
   //a is a class field
  }

later in some method of ClassB:

  a.yourMethodInClassAThatAccessesViews();

Instantiating ClassB from ClassA :

 ClassB b = new ClassB(this);

Another option is adding a public initializer to ClassB :

   public void initContext(ClassA a){
      this.a = a;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM