[英]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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.