Android - Call UI-code from a class

 •  Filed under android, ui code, class, tutorial, example

Java and the Android SDK go perfectly well together, but just like any other 'good' programming language you sometimes have to get over some rough edges. As an example, it took me almost a day to figure out how to interact with the UI thread from a class! So, I'm sharing with you this handy little Java snippet that just works. Enjoy it and stay productive!

// MainActivity.java

package me.bartsimons.helloworld

import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {  
    TextView helloText;

    @Override
    protected void onCreate(Bundle savedBundleInstance) {
        super.onCreate(savedbundleInstance);
        setContentView(R.layout.activity_main);

        helloText = (TextView) findViewById(R.id.textHelloWorld);

        SubModule moduleSub = new SubModule(this);
        moduleSub.testFunction();
    }
}
// SubModule.java

package me.bartsimons.helloworld

public class SubModule {  
    protected MainActivity context;

    public SubModule(MainActivity _context) {
        context = _context;
    }

    public void testFunction() {
        context.runOnUiThread(new Runnable() {
            context.helloText.setText("Hello world!");
        });
    }
}