Asynctask Android中的多个连续URL请求

时间:2017-08-17 08:52:53

标签: java android android-asynctask httprequest kotlin

我在请求多个连续的url http请求时遇到问题。我的应用程序没有崩溃。在此代码中使用loadUrls()函数后,它会连续执行6个url请求并将它们存储在一个数组中,但是我只能看到请求的第一个字符串响应。

fun loadUrls(){
val locationInput = “AsiaWorldExpo”
val locationCoordinatesLong = 113.947
val locationCoordinatesLat = 22.2913
val myAPIKey = "REMOVED"
val transportMode = arrayListOf("&mode=driving" ,"&mode=walking", "&mode=bicycling",
        "&mode=transit&transit_mode=bus", "mode=transit&transit_mode=subway", "mode=transit&transit_mode=train")

var requestURLArray = ArrayList<String>()
for (i in 0 until transportMode.size) {

  requestURLArray.add("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins= " +
            "$locationCoordinatesLat,$locationCoordinatesLong &destinations=$locationInput ${transportMode[i]} &key= $myAPIKey")
}
MyAsyncTask().execute(requestURLArray[0],requestURLArray[1],requestURLArray[2]
        ,requestURLArray[3], requestURLArray[4], requestURLArray[5])
}

override fun doInBackground(vararg p0: String?): String { 
        try {
            val inString = ArrayList<String>()
            for (i in 0 until p0.size) {
                val url = URL(p0[i])

                val urlConnect = url.openConnection() as HttpURLConnection
                urlConnect.connectTimeout = 7000
                inString.add(ConvertStreamToString(urlConnect.inputStream)) 
                publishProgress(inString[i])
                Log.d("APP_TEST", "" + p0[i]) //Added for debugging
                try {
                    Thread.sleep(500)
                } catch (e: InterruptedException) {}
            }
        }catch (r:Exception){}

        return " "
    }

override fun onProgressUpdate(vararg values: String?) {
    try{
        val jsonObject = ArrayList<String>()
        for (i in 0 until values.size){

            jsonObject.add(values[i]!!)
            Log.d("Testing", "" + values[i]) //Added for debugging

        }
        idTextView2.text =  jsonObject[1] 
  

编辑:上面的代码行不会将文本视图打印到UI,从jsonObject [1]到jsonObject [5]。只有jsonObject [0]有效。

    }catch (e:Exception){}
}
override fun onPostExecute(result: String?) {
}
}
    fun ConvertStreamToString(inputStream: InputStream): String{
    val bufferReader = BufferedReader(InputStreamReader(inputStream))
    var line =""
    var allString=""
    try{
        do{
            line=bufferReader.readLine()
            if (line!=null){
                allString+=line
            }
        } while (line!=null)
        inputStream.close()
    } catch (e:Exception){}
    return allString
}

这是更新的Logcat:

  

08-18 09:51:21.697 2660-3883 / com.google.android.gms W / DriveInitializer:后台初始化线程已结束

     

08-18 09:52:00.405 1369-1409 /? W / audio_hw_generic:没有向HAL提供足够的数据,预期位置772788,只写了772560

     

08-18 09:52:00.433 3297-3320 / com.companyname.emitless2 D / EGL_emulation:eglMakeCurrent:0x7ebacc5cc6e0:ver 2 0(tinfo 0x7ebadbdb9d00)

     

08-18 09:52:00.441 3297-3320 / com.companyname.emitless2 D / EGL_emulation:eglMakeCurrent:0x7ebacc5cc6e0:ver 2 0(tinfo 0x7ebadbdb9d00)

     

08-18 09:52:00.590 3297-3894 / com.companyname.emitless2 D / APP_TEST:https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins= 22.29129833333333,113.94699999999999&amp; destinations = AsiaWorldExpo&amp; mode = driving&amp; key =“REMOVED”< / p>      

08-18 09:52:00.590 3297-3297 / com.companyname.emitless2 D /测试:{“destination_addresses”:[“Cheong Wing Rd,Chek Lap Kok,Hong Kong”],“origin_addresses”:[“香港东涌易东路“],”行“:[{”元素“:[{”距离“:{”文字“:”5.9公里“,”价值“:5948},”持续时间“:{ “text”:“9分钟”,“值”:541},“状态”:“确定”}}}},“状态”:“确定”}

     

08-18 09:52:01.286 3297-3894 / com.companyname.emitless2 D / APP_TEST:https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins= 22.29129833333333,113.94699999999999&amp; destinations = AsiaWorldExpo&amp; mode = walking&amp; key =“REMOVED”< / p>      

08-18 09:52:01.287 3297-3297 / com.companyname.emitless2 D /测试:{“destination_addresses”:[“Cheong Wing Rd,Chek Lap Kok,Hong Kong”],“origin_addresses”:[“香港东涌易东路“],”行“:[{”元素“:[{”距离“:{”文字“:”5.9公里“,”价值“:5948},”持续时间“:{ “text”:“9分钟”,“值”:541},“状态”:“确定”}}}},“状态”:“确定”}

     

08-18 09:52:01.865 3297-3894 / com.companyname.emitless2 D / APP_TEST:https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins= 22.29129833333333,113.94699999999999&amp; destinations = AsiaWorldExpo&amp; mode = bicycling&amp; key =“REMOVED”< / p>      

08-18 09:52:01.865 3297-3297 / com.companyname.emitless2 D /测试:{“destination_addresses”:[“Cheong Wing Rd,Chek Lap Kok,Hong Kong”],“origin_addresses”:[“香港东涌易东路“],”行“:[{”元素“:[{”距离“:{”文字“:”5.9公里“,”价值“:5948},”持续时间“:{ “text”:“9分钟”,“值”:541},“状态”:“确定”}}}},“状态”:“确定”}

     

08-18 09:52:02.409 1672-1672 / system_process W / WindowManager:尝试删除不存在的令牌:android.os.Binder@7d40824

     

08-18 09:52:02.495 3297-3320 / com.companyname.emitless2 D / EGL_emulation:eglMakeCurrent:0x7ebacc5cc6e0:ver 2 0(tinfo 0x7ebadbdb9d00)

     

08-18 09:52:02.540 3297-3320 / com.companyname.emitless2 D / EGL_emulation:eglMakeCurrent:0x7ebacc5cc6e0:ver 2 0(tinfo 0x7ebadbdb9d00)

     

08-18 09:52:03.632 1369-1410 /? W / audio_hw_generic:没有向HAL提供足够的数据,预期位置1080247,只写了927360

     

08-18 09:52:04.458 1672-1672 / system_process W / WindowManager:尝试删除不存在的令牌:android.os.Binder@f7c5953

1 个答案:

答案 0 :(得分:2)

您正在每次迭代时创建名为inString的新实例,类型为ArrayList。因此,当您创建新实例并向其添加项时,该项始终为0.通过在循环外移动arrayList实例创建来修复它。

override fun doInBackground(vararg p0: String?): String { 
 try {
    val inString = ArrayList<String>()
    for (i in 0 until p0.size) {
        val url = URL(p0[i]) 
        val urlConnect = url.openConnection() as HttpURLConnection
        urlConnect.connectTimeout = 7000          
        inString.add(ConvertStreamToString(urlConnect.inputStream)) 
        publishProgress(inString[i])
        try {
            Thread.sleep(500)
        } catch (e: InterruptedException) {}
    }
}catch (e:Exception){}
return " "
}