4

In some case, when accessing an activity field from an anonymous class, I get NoSuchFieldError at runtime: java.lang.NoSuchFieldError: MyActivity.myField

EDIT: I'm now sure that it's an Android issue, because everything compiles correctly but resolved incorrectly at runtime. When changing to MyActivity.this.myField instead of plain myField, everything works perfect.

BTW, I rechecked and I don't have any other myField anywhere else, Also, when opening declaration in Eclipse, it goes to the intended field (myField).

The only problem is that I couldn't reproduce this in a sample project. I'm left only to state that it's a specific problem in my project, but I'm reluctant doing so and I can't publish this project.

I'll keep this open in case someone stumbles upon something similar.

Here's the code that I can publish that crashes my project but not the sample one:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MyActivity.this, myField.getName(), Toast.LENGTH_SHORT).show();
        }
    }.run();
}
5
  • Whoever votes this down, please explain the reason so I can provide a better question. Jun 16, 2012 at 14:38
  • no idea ?..but please provide code.......... Jun 16, 2012 at 14:38
  • 1
    you have down vote(i didn't) maybe because you didn't add code for example and without code we are able to do anything. Jun 16, 2012 at 14:39
  • Writing a sample code to reproduce... Jun 16, 2012 at 14:46
  • I can't create a project that reproduces this. It happens only on my project. I guess it's my fault but I can't publish this project. Bummer. Jun 16, 2012 at 19:08

1 Answer 1

0

It seems that accessing the field with the class' prefix solves it: MyActivity.this.myField

Strange. I guess it's something with Android's field resolution in runtime.

4
  • the weird thing is that it compiled . maybe you forcefully added casting on an anonymous class to the one of the outer class ? something like : ((MyActivity)this).myField... ? Jun 16, 2012 at 16:12
  • No, I didn't do anything like that. Also, in debug I pause on the problematic line and see that the field exists and has the expected content. This is so weird - I just can't reproduce it in a new sample project. Jun 16, 2012 at 19:07
  • can you please post the relevant code? it's indeed very weird. Jun 16, 2012 at 19:09
  • I can't post it all, I'll to post something. Jun 16, 2012 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.