这是我从URL读取内容然后将其添加到arraylist中的代码。当我调试它时显示sb.append(line)获取字符串但在此之后,ArrayList数据大小= 0.因此,添加sb不起作用对我来说真的很混乱。我怎么能解决它?
var arrayListData = ArrayList<String>()
var config: Config = Config()
inner class GetData: AsyncTask<Void, Void, ArrayList<String>>() {
override fun doInBackground(vararg params: Void?): ArrayList<String> {
val link = arrayOf(config.urlStatus, config.urlTongquan, config.urlBanggia)
for (i in 0 until link.size){
getContentURL(link[i])
}
return arrayListData
}
override fun onPostExecute(result: ArrayList<String>) {
super.onPostExecute(result)
Toast.makeText(this@MainActivity, result[1], Toast.LENGTH_SHORT).show()
}
}
private fun getContentURL(url: String?) : ArrayList<String> {
var sb = StringBuilder()
val url = URL(url)
val urlConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
val inputStream: InputStream = urlConnection.inputStream
val isr = InputStreamReader(inputStream)
val br = BufferedReader(isr)
var line: String? = ""
try {
do {
line = br.readLine()
if(line != null){
sb.append(line)
arrayListData.add(sb.toString())
}
}while (line != null)
br.close()
}catch (e: Exception){
Log.d("AAA", e.toString())
}
return arrayListData
}
答案 0 :(得分:0)
将您的代码更改为以下代码:
for (i in 0 until link.size){
arrayListData.add(getContentURL(link[i]))
}
然后从getContentURL()返回字符串,如下所示:
private fun getContentURL(url: String?) : String {
var sb = StringBuilder()
val url = URL(url)
val urlConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
val inputStream: InputStream = urlConnection.inputStream
val isr = InputStreamReader(inputStream)
val br = BufferedReader(isr)
var line: String? = ""
try {
do {
line = br.readLine()
if(line != null){
sb.append(line)
}
}while (line != null)
br.close()
}catch (e: Exception){
Log.d("AAA", e.toString())
}
return sb.toString()
}