Android Kotlin:java.lang.IllegalStateException

问题描述 投票:0回答:2

这是我先前发布的Kotlin using Gson to deserialize local json file的扩展名。

我希望NewsFragment.kt实例化适配器,但无法访问recyclerview id worldnews。当程序尝试执行以下代码时,我得到“ java.lang.IllegalStateException:worldnews不能为空”:

activity?.runOnUiThread {
    worldnews.adapter = MainAdapter(homeFeed)
}

NewsFragment.kt:

class NewsFragment : Fragment() {
    var arr = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }

        read_json()

    }

    fun read_json(){
        var json : String? = null

        try {
            val inputStream: InputStream = context!!.assets.open("sample.json")

            json = inputStream.bufferedReader().use { it.readText() }

            val gson = GsonBuilder().create()
            val homeFeed = gson.fromJson(json, HomeFeed::class.java)

            activity?.runOnUiThread {
                worldnews.adapter = MainAdapter(homeFeed)
            }

        } catch (e: IOException) {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_news, container, false)

        view.worldnews.layoutManager = LinearLayoutManager(activity)

        return view
    }
}
class HomeFeed(val News: List<News>)

class News(val title: String, val description: String, val time: String, val link: String)

sample.json:

{"News": [{"title": "Intesa expected to approve state-backed loan for FCA -source","description": "Italy's biggest retail bank Intesa Sanpaolo is expected to give conditional approval at a board meeting on Tuesday to a state-guaranteed $6.3 billion euro three-year loan for Fiat Chrysler (FCA), a source close to the matter said.", "time": "9:38am EDT","link": "https://www.reuters.com//article/health-coronavirus-fiat-chrylser-loan/intesa-expected-to-approve-state-backed-loan-for-fca-source-idUSS8N2B200A"}, {"title": "CANADA STOCKS-TSX opens higher on hopes of economic recovery", "description": "Canada's main stock index rose in early trade on Monday as investors looked to an eventual economic recovery from the coronavirus with more countries scaling back lockdown measures.", "time": "9:37am EDT", "link": "https://www.reuters.com//article/canada-stocks/canada-stocks-tsx-opens-higher-on-hopes-of-economic-recovery-idUSL4N2D7257"}, {"title": "Bars, gyms reopen as Iceland exits emergency coronavirus alert", "description": "Iceland eased its national alert against the coronavirus on Monday, allowing for public gatherings of up to 200 people and night clubs and gyms to reopen as the country nears complete recovery from the outbreak.", "time": "9:20am EDT", "link": "https://www.reuters.com//article/health-coronavirus-iceland/bars-gyms-reopen-as-iceland-exits-emergency-coronavirus-alert-idUSL8N2D71YX"}]}
android kotlin android-recyclerview illegalstateexception
2个回答
1
投票

您正在片段的read_json()块中调用onCreate函数,此时您的视图为空。

read_json上的调用从onCreate移动到onViewCreated

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
   read_json(view)
}

除了read_json功能中的内容之外,还将worldnews修改为view.worldnews

activity?.runOnUiThread {
   view.worldnews.adapter = MainAdapter(homeFeed)
}

0
投票

视图尚未膨胀,因此,当您执行worldnews时,read_json()不存在。

read_json()内部移动onResume

    override fun onResume() {
        super.onResume()
        read_json()
    }

否则,您只能通过首先指定膨胀视图来访问它,就像您已经在onCreate中一样:

view.worldnews.layoutManager = LinearLayoutManager(activity)
© www.soinside.com 2019 - 2024. All rights reserved.