Search code examples
javaandroidrunnableanonymous-class

How to pass or assign a value obtained in a runOnUiThread


In a subclass of WebView, I have this in an overridden method of getTitle():

      @Override
      public String getTitle() {
        Activity a = getVoTts().getActivity();
        a.runOnUiThread(new Runnable() {
            public void run() { 
                String tit = VoWebView.super.getTitle();
            }
        });


       String title = tit;  // this is what I WANT to do, it won't compile of course
       ...
       ...
      }

But the String tit is closed in an anonymous Runnable class and thus of course cannot be accessed down the method.

Is there any technique or "trick" that would allow me to pass a value obtained in an anonymous Runnable class to statements down the lines (in the same method) or assign it to a data member?


Solution

  • One way would be by declaring an instance field and using it across the whole class. For example:

    private String someText;
    
    // ...
    
    @Override
    public String getTitle()
    {
        Activity a = getVoTts().getActivity();
        a.runOnUiThread(new Runnable()
        {
            public void run()
            {  
                someText = VoWebView.super.getTitle();
            }
        });
    }
    

    EDIT:

    Regarding the reason of why you have to declare a local variable as final (or in other word, compile time constant):

    Imagine the following is valid in Java:

    @Override
    public String getTitle()
    {
        Foo f = new Foo();
    
        Button b = getButtonReference();
        b.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {  
                Boo o = f.someMethod();
            }
        });
    
        f = null;
    }
    

    At f = null, the foo object will be eligible for garbage-collected. So if you click the button, it's too late for the VM to invoke someMethod() on the foo object, since it's garbage-collected!