简体   繁体   English

Android Kotlin在其他活动中调用函数

[英]Android Kotlin call a function in other activity

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. 我在其他Activity中调用MainActivity函数,该应用程序关闭并显示错误,如下所示,请帮助解决此问题。

MainActivity function: MainActivity函数:

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) 原因:java.lang.NullPointerException:尝试在com.gph.qpon.MainActivity.checkInternet上的空对象引用上调用虚拟方法'java.lang.Object android.content.Context.getSystemService(java.lang.String)' (MainActivity.kt:148)在com.gph.qpon.qponClickedActivity.onCreate(qponClickedActivity.kt:32)

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: 一个不错的解决方案可能是像著名的iosched项目一样,具有一个ConnectivityUtils实用程序类,只需将应用程序上下文传递给它:

/**
 * 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)

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. 您应该拥有MainActivity的上下文,而不是创建一个新的上下文,或者还可以在checkInternet()方法中传递一个上下文,以便它可以在其他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. 在上面的代码中,我将baseContext替换为在方法的构造函数中传递的上下文。 Also from the other activity from which the checkInternet is called, I have send context of that activity. 另外,从调用checkInternet的其他活动中,我还发送了该活动的上下文。 Code for it is below. 下面的代码。

MainActivity.checkInternet(this)

Hope that helps. 希望能有所帮助。

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). 初始化Activity的唯一正确方法是使用Intent(但我想这不是您要在此处执行的操作)。

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): 如果我要提出一个解决方案,我建议使用扩展功能(因为您可以检查任何Context类中的连接,而不仅限于那个):

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). 声明此函数时,可以在任何上下文类中使用它(如Activity,Fragment等-它们是上下文的子类型)。 Now, how to use it? 现在,如何使用它?

class MyActivity(): Activity() {
    fun foo() {
        this.checkInternet()
    }
} 

Android Kotlin 通过 arrayList<object> 到其他活动<div id="text_translate"><p>我想在 2 个活动之间传递对象类型的 arrayList。<br> 通过以下两种方式之一:<br> 要么:有意(我没有找到放置或获得额外)类型的 arrayList !)<br> 或:OOP。 由 class 使用设置和获取功能。 但是结果还是null<br> (我不知道如何在 kotlin 类中制作 static 变量)。</p><hr><p> 我的数组列表:</p><pre> var listSongs=ArrayList&lt;songInfo&gt;()</pre><p> 里面的 songInfo class:</p><pre> var title:String?=null var authorName:String?=null var songURL:String?=null</pre><p> 通过 class:“ <strong>passing_class</strong> ”</p><p> 你喜欢什么方式?</p></div></object> - Android Kotlin passing arrayList<object> to other activity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Kotlin 通过 arrayList<object> 到其他活动<div id="text_translate"><p>我想在 2 个活动之间传递对象类型的 arrayList。<br> 通过以下两种方式之一:<br> 要么:有意(我没有找到放置或获得额外)类型的 arrayList !)<br> 或:OOP。 由 class 使用设置和获取功能。 但是结果还是null<br> (我不知道如何在 kotlin 类中制作 static 变量)。</p><hr><p> 我的数组列表:</p><pre> var listSongs=ArrayList&lt;songInfo&gt;()</pre><p> 里面的 songInfo class:</p><pre> var title:String?=null var authorName:String?=null var songURL:String?=null</pre><p> 通过 class:“ <strong>passing_class</strong> ”</p><p> 你喜欢什么方式?</p></div></object> - Android Kotlin passing arrayList<object> to other activity 具有Android视图的Kotlin调用功能 - kotlin call function with android view Android Kotlin - 如何从另一个活动调用活动方法 - Android Kotlin - How to Call Activity Method From Another Activity 来自其他活动的Android调用方法 - Android call method from an other activity android类调用其他活动按钮 - android class call other activity button Android:从其他活动调用对话框 - Android : Call Dialog from other activity 从另一个调用一个活动的 function - Call a activity's function from the other Kotlin 在没有 webView 的情况下在 Android 中调用 Javascript 函数 - Kotlin Call Javascript function in Android without webView Android:如何从 Kotlin 调用 ndk 函数? - Android: How to call ndk function from Kotlin? 如何在Kotlin Android的内部类方法中调用Activity类方法 - How to call Activity class method in inner class method in kotlin android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM