java - How to change outer variable from anonymous inner class? -
i have local variable in outer method want change anonymous inner class. how can it?
i tried solution using 1 element array described here
public class outerclass{ static public void outermethod(interface interface) { final string[] variable = new string[1]; new thread(new runnable() { @override public void run() { variable[0] = "hello"; log.i("test", variable[0]); // works, prints "hello" } }).start(); log.i("test", variable[0]); // doesn't work, null string } }
and solution using holder described here
public class outerclass{ static public void outermethod(interface interface) { final holder<string> variable = new holder<string>; new thread(new runnable() { @override public void run() { variable.held = "hello"; log.i("test", variable.held); // works, prints "hello" } }).start(); log.i("test", variable.held); // doesn't work, null string } } class holder<string> { public string held; }
but both don't work in case reason.
it might relevant, different outer method static. simplified code here, original code anonymous callback class retrofit library on android.
you're creating runnable class, never runs. need "start" it, calling start() method.
but must keep in mind, when start inside outermethod(), may not run before log method called (since run in separate thread) , order in code called not guaranteed anymore.
Comments
Post a Comment