How to pass variables to UI thread from worker thread?

Below is the code for simple get request and res variable is not available inside Ui thread. How this can be achieved in android?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Thread thread = new Thread(new Runnable(){
        @Override
        public void run(){
            try {
                String res = Utils.GetRequest("http://www.google.com");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

Answer

Okay, I found out that I haven’t declared the res variable as final.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread thread = new Thread(new Runnable(){
        @Override
        public void run(){
            try {
                final String res = Utils.GetRequest("http://www.google.com");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

Leave a Reply

Your email address will not be published. Required fields are marked *