Android Kotlin call a function in other activity

11,325

Solution 1

I would rather extract all logic to a different helper or utility class. It's a big mistake to have it within an activity if you're gonna reuse it. A pretty neat solution could be to have a ConnectivityUtils utility class like the famous iosched project has, just passing the application context to it:

/**
 * Utility methods for dealing with connectivity
 */
object ConnectivityUtils {
  fun isConnected(context: Context): Boolean {
    val connectivityManager = context.applicationContext.getSystemService(
        Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetworkInfo = connectivityManager.activeNetworkInfo
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
  }
}

Then, you just need to invoke it within any activity like this:

ConnectivityUtils.isConnected(this)

Solution 2

Either you should have the context of the MainActivity rather than creating a new one or you could also pass a context in your checkInternet() method so that it could get context in other Activity. I have modified the code below.

companion object {
    fun checkInternet(context: Context):Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = cm.activeNetworkInfo
        if (networkInfo != null && networkInfo.isConnected) {

            // alertPopUp("internet ok", "")
            return true
        }
        else {
            val title = "no Internet"
            val message = "Need Internet Service"
            // alertPopUp(title, message)

            return false
        }

    }
}

In the above code, I have replaced the baseContext with the context that I have passed in the constructor of the method. Also from the other activity from which the checkInternet is called, I have send context of that activity. Code for it is below.

MainActivity.checkInternet(this)

Hope that helps.

Solution 3

First, dont create activities directly by constructor. Activity has own lifecycle, and it's OS that manage it. The only proper way to initialize Activity is by using Intent (but I guess it's not what you want to do here).

Also, dont try to keep your Activity in any field (it leads to memory leaks). If I was to propose a solution, I would suggest use extension function (because you can check connection in any Context class, not only that one):

fun Context.checkInternet() {
   /* your code here, to use context use this */
   val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
   /* some code here */
}

When you declare this function, you can use it in any context class (like Activity, Fragment etc. - they are subtypes of context). Now, how to use it?

class MyActivity(): Activity() {
    fun foo() {
        this.checkInternet()
    }
} 
Share:
11,325

Related videos on Youtube

GPH
Author by

GPH

Updated on June 18, 2020

Comments

  • GPH
    GPH over 3 years

    I call a function of MainActivity in other Activity, the app shut down and show the error as below, please help to solve this issue.

    MainActivity function:

    fun checkInternet():Boolean {
        val cm = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = cm.activeNetworkInfo
        if (networkInfo != null && networkInfo.isConnected) {
    
            alertPopUp("internet ok", "")
            return true
        }
        else {
            val title = getString(R.string.No_Internet)
            val message = getString(R.string.need_internet_for_service)
            alertPopUp(title, message)
    
            return false
        }
    
    }
    

    Call this function in other activity:

    var internetStatus:Boolean = MainActivity().checkInternet()
    

    Error Message:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference at com.gph.qpon.MainActivity.checkInternet(MainActivity.kt:148) at com.gph.qpon.qponClickedActivity.onCreate(qponClickedActivity.kt:32)

    • Cililing
      Cililing over 5 years
      Just to be sure - are you creating your Activity directly by constructor?
    • EpicPandaForce
      EpicPandaForce over 5 years
      He is creating his Activity directly with a constructor for whatever unknown reason
  • Tim
    Tim over 5 years
    MainActivity() no. Bad
  • Harsh Jain
    Harsh Jain over 5 years
    @TimCastelijns I know that why I have mentioned that either you should have the context of Main Activity. But I also think a static method would do the work? Also, can you share your thoughts on this too? It would be helpful.
  • Tim
    Tim over 5 years
    this is not a static method. Kotlin does not even have static methods. You are initializing an activity with () which is bad
  • Harsh Jain
    Harsh Jain over 5 years
    @TimCastelijns I mean through companion object. And yes this is not through this. but I have also written the code for it too.
  • Tim
    Tim over 5 years
    you're not reading what I'm saying. You are initializing an activity with ()
  • Harsh Jain
    Harsh Jain over 5 years
    @TimCastelijns That I know, I have to call the method of another activity by taking an instance of that Activity. So I used () but I have also made the code through companion object which would not require MainActivity().checkInternet(). It would simply be called through MainActivity.checkInternet().
  • Tim
    Tim over 5 years
    So I used () - yes that is the problem. Remove it and don't suggest people do that. You should never manually instantiate an activity by calling the constructor
  • Harsh Jain
    Harsh Jain over 5 years
    @TimCastelijns Sure I'll do that
  • GPH
    GPH over 5 years
    thank you! I think our method is the best. I am would like to use ConnectivityUtils.isConnected(this) inside a fragment of Mainactivity. What should I write for ConnectivityUtils.isConnected(______)?
  • GoRoS
    GoRoS over 5 years
    Fragments have a method to get the Activity they are associated with. However, before calling that method ensure activity is not null, or just call ConnectivityUtils.isConnected(activity!!) --> in Java it's a getter method called getActivity()
  • GPH
    GPH over 5 years
    thank you so much! I test the code ConnectivityUtils.isConnected(activity!!) and ConnectivityUtils.isConnected(this.context!!) are also works well. Could you please let me know the difference between activity!! and this.context!!?
  • GoRoS
    GoRoS over 5 years
    An Activity extends from a Context, however you could use either of them without any problem. Perhaps I'd go for the context. Fragments can be hosted in any Object, and Android call those objects "hosts". They must extend from FragmentHostCallback abstract class, which has the 'getActivity()` and getContext() methods among other ones. So these methods just return the Activity and Context of the host object if they have one assigned. Source: android.googlesource.com/platform/frameworks/support/+/refs/‌​…