0

I am trying to call a simple function in a separate class in Kotlin in Android:

public class TestOfAClass: AppCompatActivity()  {
      public fun ThisIsATest(thisTest: String) {
           print(thisTest)
    }
}

but in when I have:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            ThisIsATest("Hello World")
        }
    }
}

I get am Unresolved reference: ThisIsaTest

So how can I call a function from a different class?

Michal
  • 15,429
  • 10
  • 73
  • 104
Winny
  • 131
  • 9
  • Seems that `ThisIsATest` is a class method, which you didn't specify in your question. – Alexey Soshin Mar 05 '20 at 23:26
  • 3
    "So how can I call a function from a different class?" -- your function is an instance function, and so you would need an instance of the other class first, then you call the function on that instance. – CommonsWare Mar 05 '20 at 23:35
  • Are you really trying to call a method in another activity? Because that might be a much deeper understanding issue than just initializing an object on which you would call an instance method. Maybe you could elaborate on your thoughts - what you have and what you want to have. – Michal Mar 06 '20 at 15:39
  • You cannot directly invoke the method of a different activity. You need to use startActivityForResult, and more importantly you probably don't even need 2 Activities if that's what you need (unless you have an assignment at school that tells you to do this – EpicPandaForce Mar 06 '20 at 18:05

1 Answers1

0

The method you want to call is an instance method, the easiest answer is:

class MainActivity : AppCompatActivity() {

….
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            TestOfAClass().ThisIsATest("Hello World")
        }
    ))

the better answer is to rename your method to camel case:

     public fun thisIsATest(thisTest: String) {
           print(thisTest)
    }
}

That way you know its a method and not a class.


But if you are trying to communicate between two Activities, this is not how to do it. There are a few other options, one is using startActivityForResult:

https://developer.android.com/training/basics/intents/result

How to manage startActivityForResult on Android?

Blundell
  • 75,855
  • 30
  • 208
  • 233
  • I think there is a much deeper question in the fact that the OP does not understand Android and wants to call a method of another activity. – Michal Mar 06 '20 at 15:37
  • 2
    For sure. Sometimes though getting it working is what makes you realise its a mistake. Added a hint at that, thanks for the prompt @Michal – Blundell Mar 06 '20 at 17:52