0

I'm using Kotlin in android studio to make an app.

In my main activity I have a function changeText() that changes the text of a textbox. I have a class that I'm implementing called VerificationListener() that when created will do things then call onVerified(), however I cannot call changeText from onVerified, is there a way to do so? The example I'm working off of is in Java and does it.

Example I'm working off of

public void onVerified() {
            mIsVerified = true;
            Log.d(TAG, "Verified!");
            hideProgressAndShowMessage(R.string.verified);
            showCompleted();}

Above is within the class, below is just sitting in the activity

private void showCompleted() {
    ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
    checkMark.setVisibility(View.VISIBLE);
}
  • Is your implementation of VerificationListener an inner class of your main activity? – pablobu May 11 '18 at 20:07
  • You need to clarify your question. Almost nothing in your description matches the code you provided. Where is the `changeText()` method? Where is it called from? Why are you posting the example which you're saying doesn't have the issue? What do you mean by " I cannot call changeText from onVerified" - is it a compilation issue, crash or something else? – Dennis K May 12 '18 at 08:59

2 Answers2

0

You can't access the UI from a background thread, Kotlin or not. You have to run this on the UI thread:

runOnUiThread {
    val checkMark: ImageView = findViewById(R.id.checkmarkImage)
    checkMark.visibility = View.VISIBLE
}
Cristan
  • 12,083
  • 7
  • 65
  • 69
0

If by "I cannot call changeText from onVerified" you mean that you have a VerificationListener as a separate standalone class and from that class you cannot call methods on the Activity, you should either a) make the VerificationListener an inner class of the Activity, b) pass your activity into the VerificationListener when it's created (be aware of the lifecycle) c) implement some messaging solution (broadcast receiver, startActivity + onIntent(), observable, or even an event bus (not advisable). Here is a sample implementation for b:

class MyActivity : Activity(), VerificationListener.OnVerifiedCallback {

    fun onVerified() {
        changeText()
    }

    override fun onCreate(state: Bundle) {
        super.onCreate(state)

        VerificationListener(this).doStuff()

    }

}


class VerificationListener(internal var callback: OnVerifiedCallback) {
    interface OnVerifiedCallback {
        fun onVerified()
    }

    fun whenSomethingGetsVerified() {
        doThings()
        callback.onVerified()
    }
}

EDIT: forgot you are using Kotlin, changed to Kotlin implementation

Dennis K
  • 1,828
  • 1
  • 16
  • 27