【发布时间】:2020-09-19 20:55:11
【问题描述】:
我知道这听起来很奇怪。
因此,在我的 MainActivity 中,我声明了一个对象数组 SongInfo,如下所示:
class SongInfo {
lateinit var title: String
lateinit var contentId: String
lateinit var filepath: String
}
这就是我在 MainActivity 中声明数组的方式:
lateinit var songInfo: Array<SongInfo?>
所以,现在当我按下一个按钮时,这个按钮的监听器会执行这个:
searchButton.setOnClickListener {
val cursor = contentResolver.query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
arrayOf(
"_id",
"_data",
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DURATION
),
"is_music == 1",
null, null
)
songInfo = arrayOfNulls(cursor!!.count)
for (index in songInfo.indices) {
songInfo[index] = SongInfo()
Log.d(tag, "searchButton: $index")
}
adapter = listMusicService.listMusic(cursor)
adapter.notifyDataSetChanged()
}
ListMusicService 类如下所示:
class ListMusicService(val context: Context, private var adapter: ArrayAdapter<Any>) {
private val tag = "MusicShare/ListMusicService"
fun listMusic(cursor: Cursor): ArrayAdapter<Any> {
val activity = MainActivity()
adapter.clear()
val songInfo = arrayOfNulls<SongInfo>(cursor.count)
var duration: Double
var index = 0
while (cursor.moveToNext()) {
duration = ((cursor.getDouble(4) / 600).roundToInt() / 100).toDouble()
adapter.add(cursor.getString(3) + ": " + cursor.getString(2) + " (" + duration + ")")
val filepath = File(cursor.getString(1))
Log.d(tag, "searchMusic: writing songInfo")
songInfo[index] = SongInfo()
songInfo[index]!!.title = filepath.name
songInfo[index]!!.filepath = filepath.absolutePath
activity.songInfo[index]!!.filepath = filepath.absolutePath
songInfo[index]!!.contentId = cursor.getString(0)
index++
}
return adapter
}
}
现在按下searchButton 会导致kotlin.UninitializedPropertyAccessException: lateinit property songInfo has not been initialized。
但我不明白为什么,因为在searchButton 的侦听器方法中,我正在初始化数组的每个对象。有谁知道为什么会发生这种情况以及可能出了什么问题?
编辑:创建ListMusicService:
val listMusicService = ListMusicService(this, adapter)
【问题讨论】:
标签: java android arrays kotlin