Android科特林:java.lang.IllegalStateException

Android Kotlin: java.lang.IllegalStateException

这是我之前发布的 的扩展。

我想 NewsFragment.kt 实例化一个适配器,但无法访问 recyclerview id worldnews。当程序尝试执行以下代码时,我得到 "java.lang.IllegalStateException: worldnews must not be null":

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 .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"}]}

视图还没有膨胀,所以执行read_json()worldnews不存在。

read_json() 移到 onResume 内。

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

否则你只能通过先指定膨胀视图来访问它,就像你已经在 onCreate 中所做的那样:

view.worldnews.layoutManager = LinearLayoutManager(activity)

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

将 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)
}