在Google Kotlin调试入门Codelab中遇未解析引用错误求助
未解析引用错误排查
在完成Google Kotlin调试入门Codelab时,遇到无法解决的未解析引用错误,已查阅相关内容卡滞两天,求指点问题所在。
原始代码:
fun division() = with(Handler(Looper.getMainLooper())){ val numerator = 60 var denominator = 4 repeat(4) {i-> postDelayed({ findViewById<TextView>(R.id.division_textview).setText("${numerator / denominator}") Log.v(TAG, "${numerator / denominator}") denominator-- },i*3000L) } } fun logging() { Log.e(TAG, "ERROR: a serious error like an app crash") Log.w(TAG, "WARN: warns about the potential for serious errors") Log.i(TAG, "INFO: reporting technical information, such as an operation succeeding") Log.d(TAG, "DEBUG: reporting technical information useful for debugging") Log.v(TAG, "VERBOSE: more verbose than DEBUG logs") } class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"this where the app crashed before") val helloTextView: TextView = findViewById(R.id.division_textview ) Log.d(TAG, "this should be logged if the bug is fixed ") helloTextView.text= "Hello, debugging " logging() division() } }
问题分析及解决方案:
- 未定义TAG常量:所有
Log调用中的TAG未声明,需在MainActivity类内添加常量定义:private val TAG = "MainActivity" - 函数作用域错误:
division()和logging()定义在类外部,无法访问Activity的视图资源及成员,需将这两个函数移至MainActivity类内部作为成员函数。 - Handler相关类未导入:确保代码顶部导入
android.os.Handler和android.os.Looper,避免类未解析。 - findViewById作用域问题:移至类内部后,
postDelayed回调中才能正确调用findViewById访问Activity的视图。
修正后的代码示例:
import android.os.Handler import android.os.Looper import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { private val TAG = "MainActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"this where the app crashed before") val helloTextView: TextView = findViewById(R.id.division_textview ) Log.d(TAG, "this should be logged if the bug is fixed ") helloTextView.text= "Hello, debugging " logging() division() } fun division() = with(Handler(Looper.getMainLooper())){ val numerator = 60 var denominator = 4 repeat(4) {i-> postDelayed({ findViewById<TextView>(R.id.division_textview).text = "${numerator / denominator}" Log.v(TAG, "${numerator / denominator}") denominator-- },i*3000L) } } fun logging() { Log.e(TAG, "ERROR: a serious error like an app crash") Log.w(TAG, "WARN: warns about the potential for serious errors") Log.i(TAG, "INFO: reporting technical information, such as an operation succeeding") Log.d(TAG, "DEBUG: reporting technical information useful for debugging") Log.v(TAG, "VERBOSE: more verbose than DEBUG logs") } }
内容的提问来源于stack exchange,提问作者codingNoob
相关产品推荐
相关产品推荐

