11

Inner class is Adapter, inner-inner class is Listener. How to access (obscured) Adapter members/methods from Listener?

list.setAdapter(new Adapter() {
  public View getView() {
    // ...
    button.setListener(new Listener() {
      public void onClick() {
        Adapter.this.remove(item);
      }
    );
  }
});

Normally to access the outer classes members, you just say Outer.this.member, but in this case it gave me the following error (using the actual class):

error: not an enclosing class: ArrayAdapter

So how are you supposed to access an inner class members from an inner-inner class? I don't like multi-level nested anonymous classes, but in this case I'm learning a new API and am not sure of a cleaner way yet. I already have a workaround but wanted to know anyways. remove() isn't really obscured by the inner-inner class so specifying the class isn't really necessary in this case, but wanted to make it clear in the code exactly where this remove() method is. I also wanted to know in case it is obscured. I believe using Outer.$6.remove() would work, but I don't believe it should be that way either.

Chloe
  • 25,162
  • 40
  • 190
  • 357

3 Answers3

13

Assign this to a variable, then access that one of innermost class.

list.setAdapter(new Adapter() {
  public View getView() {
    final Adapter that = this;
    button.setListener(new Listener() {
      public void onClick() {
        that.remove(item);
      }
    );
  }
});

I'm not sure what would be a good naming here. Perhaps adapter?

Chloe
  • 25,162
  • 40
  • 190
  • 357
skrat
  • 5,518
  • 3
  • 32
  • 48
  • I see. I thought there would be a language syntax to use in order to get at Adapter that I didn't know about. BTW `that` would have to be final. – Chloe Apr 01 '12 at 00:03
  • 1
    I prefer this approach as it is easily readable and explicit. – skrat Apr 01 '12 at 00:09
  • I get a compilation error on the line Adapter that = Adapter.this; (Adapter is not a enclosing class). Instead you should rather be saying final Adapter that=this.. if at all.. – sethu Jan 09 '13 at 13:08
1

Just call the method on Adapter directly:

list.setAdapter(new Adapter() {
  public View getView() {
    // ...
    button.setListener(new Listener() {
      public void onClick() {
        remove(item); // <-- this will call Adapter's method of the anonymous class
      }
    );
  }
});
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

its simple as this: try outer.remove without this class pointer

GingerHead
  • 8,130
  • 15
  • 59
  • 93