Home > Mobile >  Can't get text from URL
Can't get text from URL

Time:01-29

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 RecylerView instead of ListViewand 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("и&#774;", "й")
                    .replace("И&#774;", "Й")
                    .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

  • Related