I think my question is pretty simple, but I just started my road in android, so it's a big problem right now. Anyway, I want to read text from url, convert it to array and display as ListView.
Here's part of my code:
private fun getSongList() {
Executors.newSingleThreadExecutor().execute() {
val songList =
URL("https://vivalaresistance.ru/radio/stuff/vlrradiobot.php?type=getPlaylist").readText(
Charset.forName("windows-1251")
)
.replace("й", "й")
.replace("Й", "Й")
.split("\n").toTypedArray()
}
val list = view?.findViewById<ListView>(R.id.list)
val arrayAdapter =
ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, songList)
list?.adapter = arrayAdapter
}
The problem is in declaring values, I guess.
What should I change to make this whole thing work?
CodePudding user response:
Several things are wrong with your code :
- You don't actually call the url, you are just defining it without opening a connection with a
HttpUrlConnection - You are updating UI code in
Executors.newSingleThreadExecutor().execute()which is a background thread, you should always update UI on UI thread - It's just about optimisation but you better use
RecylerViewinstead ofListViewand dataBinding instead of view reference and you shouldn't have UI code and background code in same class
With that said a correct way to implement your function using anonymous asyncTask would be :
private fun getSongList() {
val task = object : AsyncTask<Void, Void, Array<String>>() {
override fun doInBackground(vararg params: Void): Array<String> {
val url = URL("https://vivalaresistance.ru/radio/stuff/vlrradiobot.php?type=getPlaylist")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
val songList = BufferedReader(InputStreamReader(connection.inputStream))
connection.disconnect()
return songList
.readText()
.replace("й", "й")
.replace("Й", "Й")
.split("\n").toTypedArray()
}
override fun onPostExecute(result: Array<String>) {
val list = view?.findViewById<ListView>(R.id.list)
val arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1,result)
list?.adapter = arrayAdapter
}
}
task.execute()
}
Assuming that you want to perform split/replace operations on the result and not the url itself
