class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var queue: RequestQueue
private val movies = ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
queue = Volley.newRequestQueue(application)
binding.btnConnect.setOnClickListener {
val url = "https://yts.torrentbay.to/api/v2/list_movies.json?sort=rating&limit=30"
val request = JsonObjectRequest(
Request.Method.GET,
url,
null,
{
movies.clear()
parseJason(it)
Toast.makeText(application, movies.toString()
.replace(",", "\n")
.replace("[\\[\\]]".toRegex(), ""), Toast.LENGTH_LONG).show()
binding.listMovies.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, movies)
},
{
Toast.makeText(application, it.toString(), Toast.LENGTH_LONG).show()
}
)
queue.add(request)
}
}
binding = ActivityMainBinding.inflate(layoutInflater)
: 뷰바인딩
queue = Volley.newRequestQueue(application)
: Volley - 요청 객체 저장을 위한 큐 생성
val request = JsonObjectRequest(
Request.Method.GET,
url,
null,
{
movies.clear()
parseJason(it)
Toast.makeText(application, movies.toString()
.replace(",", "\n")
.replace("[\\[\\]]".toRegex(), ""), Toast.LENGTH_LONG).show()
binding.listMovies.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, movies)
},
{
Toast.makeText(application, it.toString(), Toast.LENGTH_LONG).show()
}
)
JsonObjectRequest()
를 통해 JSON 데이터를 받아옴Request.Method.GET
: GET 방식으로 받아옴.replace(",", "\n").replace("[\\[\\]]".toRegex(), "")
: 첫 번째 인자를 두 번재 인자로 대체 binding.listMovies.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, movies)
private fun parseJason(obj: JSONObject) {
val items = obj.getJSONObject("data").getJSONArray("movies")
for (i in 0 until items.length()) {
val item: JSONObject = items[i] as JSONObject // as : TypeCasting
val title = item.getString("title_long")
movies.add(title)
}
}