NewsViewModel.kt 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package io.r_a_d.radio2.ui.news
  2. import android.util.Log
  3. import androidx.lifecycle.ViewModel
  4. import androidx.recyclerview.widget.RecyclerView
  5. import io.r_a_d.radio2.Async
  6. import io.r_a_d.radio2.tag
  7. import org.json.JSONArray
  8. import org.json.JSONObject
  9. import java.net.URL
  10. import java.text.SimpleDateFormat
  11. import java.util.*
  12. import kotlin.collections.ArrayList
  13. class NewsViewModel : ViewModel() {
  14. val newsArray : ArrayList<News> = ArrayList()
  15. private val urlToScrape = "https://r-a-d.io/api/news"
  16. private val scrape : (Any?) -> Unit =
  17. {
  18. val t = URL(urlToScrape).readText()
  19. val result = JSONArray(t)
  20. newsArray.clear()
  21. for (n in 0 until result.length())
  22. {
  23. val news = News()
  24. news.title = (result[n] as JSONObject).getString("title")
  25. news.author = (result[n] as JSONObject).getJSONObject("author").getString("user")
  26. news.text = (result[n] as JSONObject).getString("text")
  27. news.header = (result[n] as JSONObject).getString("header")
  28. val formatter6 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
  29. news.date = formatter6.parse((result[n] as JSONObject).getString("updated_at")) ?: Date()
  30. Log.d(tag, "$news")
  31. newsArray.add(news)
  32. }
  33. }
  34. fun fetch(root: androidx.swiperefreshlayout.widget.SwipeRefreshLayout? = null, viewAdapter: RecyclerView.Adapter<*>? = null)
  35. {
  36. val post : (parameter: Any?) -> Unit = {
  37. root?.isRefreshing = false
  38. viewAdapter?.notifyDataSetChanged()
  39. }
  40. Async(scrape, post)
  41. }
  42. }