简体   繁体   中英

How to use Activity method in another class

This constructor doesn't work for me, ie:when i create a MainActivity object in the other class via this constructor, its throwing a null pointer exception

private static MainActivity instance;
public  MainActivity getInstance()
    {
     return  instance;   
    }

Your instance is not initialized when you call getInstance so it's default value is null. To avoid NPE, you have to give a value to your instance, you can for example call the constructor of MainActivity
I think you are trying the Singleton Pattern, do you can check the code below

private static MainActivity instance = new MainActivity();
public  MainActivity getInstance(){

     return  instance;   
}
class MyActivity : ExternalListener {
   val externalClass = ExternalClass(this)
   override fun printResults() {
      println("printing details from Activity: ".plus(this.javaClass.name))
   }
}

interface ExternalListener {
   fun printResults()
}

class ExternalClass(val listener: ExternalListener) {
   fun printResults() {
      listener.printResults()
   }
}

So your MyActivity implements an interface ExternalListener which you pass as an argument to your ExternalClass, in which you use MyActivity. printDetails() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM