Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Kotlin中使用Handler类会使我的android应用程序崩溃_Android_Kotlin_Handler - Fatal编程技术网

在Kotlin中使用Handler类会使我的android应用程序崩溃

在Kotlin中使用Handler类会使我的android应用程序崩溃,android,kotlin,handler,Android,Kotlin,Handler,当我从处理程序类调用方法时,我的应用程序无法在emulator中打开。我试着注释掉代码中的处理程序部分,应用程序正常启动。我需要帮助查找代码中的错误或其他地方。 我是初学者,所以我在构建一些基本的东西,一个可运行的东西,可以让图片在屏幕的随机部分可见,下面是方法: fun goKenny(){ runnable = object : Runnable{ override fun run() { for (kenny in kennyList){

当我从处理程序类调用方法时,我的应用程序无法在emulator中打开。我试着注释掉代码中的处理程序部分,应用程序正常启动。我需要帮助查找代码中的错误或其他地方。 我是初学者,所以我在构建一些基本的东西,一个可运行的东西,可以让图片在屏幕的随机部分可见,下面是方法:

fun goKenny(){

    runnable = object : Runnable{
        override fun run() {

            for (kenny in kennyList){
                kenny.visibility = View.INVISIBLE
            }

            var random = Random(8 - 0)
            var randomIndex = random.nextInt()

            kennyList[randomIndex].visibility = View.INVISIBLE

            handler.postDelayed(runnable,300)

        }

    }
    handler.post(runnable)

}
以下是我的其余代码:

class MainActivity : AppCompatActivity() {


    private var handler : Handler = Handler()
    private var runnable : Runnable = Runnable {  }
    private var kennyList = tableLayout.children.toList()


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

        val sharedPreferences =
        this.getSharedPreferences("com.example.kennygame", android.content.Context.MODE_PRIVATE)

        //sharedPreferences.edit().putInt("High Score",score).apply();

        goKenny()

        object : CountDownTimer(10000, 1000) {
            override fun onFinish() {
                Toast.makeText(applicationContext, "Time's Up", Toast.LENGTH_LONG).show()
                timeView.text = "TIME'S UP"

                var highScore = sharedPreferences.getInt("High Score", 0)


                val sendHighScore = Intent(applicationContext, Main2Activity::class.java)

                sendHighScore.putExtra("Score", score)
                startActivity(sendHighScore)

            }

            override fun onTick(millisUntilFinished: Long) {
                timeView.text = "TIME: " + millisUntilFinished / 1000
            }


        }.start()


    }
}
错误跟踪:

2019-12-12 04:35:48.911 8789-8789/? I/zygote: Not late-enabling -Xcheck:jni (already on)
2019-12-12 04:35:48.937 8789-8789/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
2019-12-12 04:35:49.305 8789-8789/com.example.kennygame D/AndroidRuntime: Shutting down VM
2019-12-12 04:35:49.310 8789-8789/com.example.kennygame E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.kennygame, PID: 8789
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kennygame/com.example.kennygame.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2718)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
        at android.content.Context.obtainStyledAttributes(Context.java:655)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
        at com.example.kennygame.MainActivity._$_findCachedViewById(Unknown Source:25)
        at com.example.kennygame.MainActivity.<init>(MainActivity.kt:22)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1173)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6541) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
2019-12-1204:35:48.911 8789-8789/?I/合子:未延迟启用-Xcheck:jni(已启用)
2019-12-12 04:35:48.937 8789-8789/? W/zygote:使用默认值X86的X86的意外CPU变量
2019-12-12 04:35:49.305 8789-8789/com.example.kennygame D/AndroidRuntime:关闭虚拟机
2019-12-12 04:35:49.310 8789-8789/com.example.kennygame E/AndroidRuntime:致命异常:main
进程:com.example.kennygame,PID:8789
java.lang.RuntimeException:无法实例化activity ComponentInfo{com.example.kennygame/com.example.kennygame.MainActivity}:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2718)上
位于android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
位于android.app.ActivityThread.-wrap11(未知来源:0)
在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
位于android.os.Handler.dispatchMessage(Handler.java:105)
位于android.os.Looper.loop(Looper.java:164)
位于android.app.ActivityThread.main(ActivityThread.java:6541)
位于java.lang.reflect.Method.invoke(本机方法)
在com.android.internal.os.Zygote$MethodAndArgsCaller.run上(Zygote.java:240)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
原因:java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”
位于android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
在android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)中
位于android.content.Context.ActainStyledAttributes(Context.java:655)
位于androidx.appcompat.app.appcompatedelegateimpl.createSubDecor(appcompatedelegateimpl.java:692)
在androidx.appcompat.app.appcompatedelegateimpl.ensureubdecor(appcompatedelegateimpl.java:659)
位于androidx.appcompat.app.appcompatedelegateimpl.findViewById(appcompatedelegateimpl.java:479)
在androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)上
在com.example.kennygame.MainActivity.\u$\ u findCachedViewById(未知来源:25)
在com.example.kennygame.MainActivity上。(MainActivity.kt:22)
位于java.lang.Class.newInstance(本机方法)
位于android.app.Instrumentation.newActivity(Instrumentation.java:1173)
在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2708)上
位于android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
位于android.app.ActivityThread.-wrap11(未知来源:0)
在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
位于android.os.Handler.dispatchMessage(Handler.java:105)
位于android.os.Looper.loop(Looper.java:164)
位于android.app.ActivityThread.main(ActivityThread.java:6541)
位于java.lang.reflect.Method.invoke(本机方法)
在com.android.internal.os.Zygote$MethodAndArgsCaller.run上(Zygote.java:240)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

谢谢你的帮助

试试这样的安全电话

private val handler : Handler by lazy { Handler() }
handler?.post(可运行)

更新1:


看起来问题在于您试图设置视图的可见性。您将获得空对象引用

若要验证,请尝试注释
kenny.visibility=View.INVISIBLE
kennyList[randomIndex].visibility=View.INVISIBLE
。它应该在注释后成功运行

更新2:

您在for循环中使用的是
kennyList
,该循环源自
tableLayout
。请尝试注释“for”循环,并让我知道它是否运行

更新3:

private var kennyList=tableLayout.children.toList()中似乎存在问题

尝试其他解决方案,如:

    private lateinit var kennyList: ArrayList<View>

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        for (index in 0 until tableLayout.childCount) {
            val nextChild: View = tableLayout.getChildAt(index)
            kennyList.add(nextChild)
        }
        ...
    }
private lateinit var kennyList:ArrayList
重写创建时的乐趣(savedInstanceState:Bundle?){
...
for(在0中索引,直到tableLayout.childCount){
val nextChild:View=tableLayout.getChildAt(索引)
kennyList.add(下一个孩子)
}
...
}

如果仍然获得空对象引用,请尝试在
onCreate()中添加
val tableLayout=findViewById(R.id.tableLayout)
,然后再添加
for
循环。

问题在于处理程序初始化。若要构造不带参数构造函数的处理程序,必须在活动的后期进行。惰性初始化将是一个简单且最好的解决方案

像这样更改处理程序初始化

private val handler : Handler by lazy { Handler() }

注意:还要检查您是否为视图设置了正确的可见性,因为您正在设置
视图。在for循环for循环后中都不可见,这是多余的,或者您在那里做了一些错误的事情。

问题是视图不创建何时调用: private var kennyList=tableLayout.children.toList() 应在onCreate()中调用tableLayout.children.toList()

我重构您的代码:

private val kennyList: MutableList<View> = mutableListOf()

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

    // init
    kennyList.clear()
    kennyList.addAll(tableLayout.children.toList())

    val sharedPreferences =
        this.getSharedPreferences("com.example.kennygame", android.content.Context.MODE_PRIVATE)

嗯,没什么变化,上面写着:handler类型的非空接收器上不必要的安全调用。你能提供你得到的错误日志吗?好吧,我没有得到任何错误,就是这样