Это расширение Kotlin с использованием Gson для десериализации локального json файла , который я опубликовал ранее.
Я хочу, чтобы 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 $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"}]}