1

I have a local variable in my outer method that I want to change from an anonymous inner class. How can I do it?

I tried the solution using a one 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 the solution using a 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 my case for some reason.

It might be relevant, but what is different is that my outer method is static. I also simplified my code here, the original code was for an anonymous Callback class from the Retrofit library on Android.

Community
  • 1
  • 1
J. Doe
  • 85
  • 12

2 Answers2

3

You're creating a Runnable class, but it actually never runs. You need to "start" it, by calling its start() method.

But you must also keep in mind, that when you start it inside the outerMethod(), it may not run before the Log method is called (since it will run in a separate thread) and the order in which the code is called is not guaranteed anymore.

radoh
  • 4,554
  • 5
  • 30
  • 45
  • This isn't my actual code I've simplified it so I forgot to put the start. If everything seems fine do you want me to put the actual code instead ? – J. Doe Feb 06 '16 at 00:24
  • I've edited my answer for additional comment about the threads and order in which subsequent code is executed. – radoh Feb 06 '16 at 00:31
  • Thank you so much that was indeed the problem! The log was run before the thread modified the variable. I added a join() to the thread to wait until it finishes to print the log, and that now works like a charm ! – J. Doe Feb 06 '16 at 00:39
0

Check synchronisation of your threads. Use Object.wait() or synchronized keyword. Your main thread does not wait until new created thread initializes variable. It should wait for this to finish.

And by the way your class could not be inner class. See here

Community
  • 1
  • 1