[TIL]20221128 - VolleyWithRecyclerView

Jimin·2022년 11월 29일
0

Volley

  • 상수 및 변수 추가
  • queue는 init에서 초기화하므로 lateinit 필요 없음
  • getApplication() 대신 getApplication<Application>().applicationContext 사용 가능

//SongViewModel.kt

class SongViewModel(application: Application) : AndroidViewModel(application) {
    data class Song (var id: Int, var title: String, var singer: String)

    companion object {
        const val  QUEUE_TAG = "SongVolleyREquest"
    }

    private val songs = ArrayList<Song>()
    private val _list = MutableLiveData<ArrayList<Song>>()
    val listL: LiveData<ArrayList<Song>>
        get() = _list

    private var queue: RequestQueue

    init {
        _list.value = songs
        queue = Volley.newRequestQueue(getApplication())
    }

    fun requestSong() {
        val url = "https://expreesongdb-hoaos.run.goorm.io"

        val request = JsonArrayRequest(
            Request.Method.GET,
            url,
            null,
            {
//                Toast.makeText(getApplication(), it.toString(), Toast.LENGTH_LONG).show()
                songs.clear()
                parseJson(it)
                _list.value = songs
            },
            {
                Toast.makeText(getApplication(), it.toString(), Toast.LENGTH_LONG).show()

            }
        )

        request.tag = QUEUE_TAG
        queue.add(request)
    }

    override fun onCleared() {
        super.onCleared()
        queue.cancelAll(QUEUE_TAG)
    }

    private fun parseJson(items: JSONArray) {
        for (i in 0 until items.length()) {
            val item = items[i] as JSONObject // 타입캐스팅 안 해주면 ANY형
            val id = item.getInt("id")
            val title = item.getString("title")
            val singer = item.getString("singer")

            songs.add(Song(id, title, singer))
        }
    }
}

//MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var binding : ActivityMainBinding
    private lateinit var model : SongViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        model = ViewModelProvider(this)[SongViewModel::class.java]
        model.requestSong()
    }
}

0개의 댓글