2017-10-19 11 views
0

This AsyncTask class should be static or leaks might occurリークのないAsyncTask

なぜ私のAsyncTaskは機能しませんか?

コール:PlacesTask(this).execute(...)

コード:

private class PlacesTask internal constructor(activity: MainActivity) : AsyncTask<String, Int, String>() { 
     var data: String? = null 
     private val mRef: WeakReference<MainActivity> = WeakReference(activity) 

     override fun doInBackground(vararg url: String): String? { 
      try { 
       data = MainActivity().downloadUrl(url[0]) 
      } catch (e: Exception) { 
       Log.d("Background Task", e.toString()) 
      } 
      return data 
     } 

     override fun onPostExecute(result: String) { 
      val asyncTaskLeak = mRef.get() 
      if (asyncTaskLeak != null) SetPlaceTask().execute(result) 
     } 
    } 

    private class SetPlaceTask : AsyncTask<String, Int, List<HashMap<String, String>>>() { 
     var places: List<HashMap<String, String>>? = null 

     override fun doInBackground(vararg jsonData: String): List<HashMap<String, String>>? { 
      try { 
       places = PlaceJSONParser().parse(JSONObject(jsonData[0])) 
      } catch (e: Exception) { 
       Log.d("Exception", e.toString()) 
      } 
      return places 
     } 

     override fun onPostExecute(list: List<HashMap<String, String>>) { 
      ... 
     } 
    } 

@Throws(IOException::class) 
    private fun downloadUrl(strUrl: String): String { 
     var data = "" 
     var iStream: InputStream? = null 
     var urlConnection: HttpURLConnection? = null 
     try { 
      urlConnection = URL(strUrl).openConnection() as HttpURLConnection 
      urlConnection.connect() 
      iStream = urlConnection.inputStream 
      val br = BufferedReader(InputStreamReader(iStream!!)) 
      val sb = StringBuilder() 
      var line: String? = null 
      while ({line = br.readLine(); line }() != null) sb.append(line) 
      data = sb.toString() 
      br.close() 
     } catch (e: Exception) { 
      Log.d("downloading url", e.toString()) 
     } finally { 
      if (iStream != null) iStream.close() 
      if (urlConnection != null) urlConnection.disconnect() 
     } 
     return data 
    } 

Error: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter result

助けてください。私は何が欠けていますか?

答えて

0

私は理解しました。

  1. AsyncTaskからstatic
  2. AsyncTask移動する必要があります - >companion object {}
  3. WeakReference - 漏れのないAsyncTaskについては

例(グッドEXP。):AsyncTask漏れのない

override fun onPause() { 
     super.onPause() 
     ... 
     when { 
      placesTask != null -> { 
       placesTask!!.cancel(true) 
       placesTask = null 
      } 
      setPlacesTask != null -> { 
       setPlacesTask!!.cancel(true) 
       setPlacesTask = null 
      } 
     } 
} 
    ... 

    @Throws(IOException::class) 
    private fun downloadUrl(strUrl: String): String { 
     var data = "" 
     var iStream: InputStream? = null 
     var urlConnection: HttpURLConnection? = null 
     try { 
      urlConnection = URL(strUrl).openConnection() as HttpURLConnection 
      urlConnection.connect() 
      iStream = urlConnection.inputStream 
      val br = BufferedReader(InputStreamReader(iStream!!)) 
      val sb = StringBuilder() 
      var line: String? = null 
      while ({line = br.readLine(); line }() != null) sb.append(line) 
      data = sb.toString() 
      br.close() 
     } catch (e: Exception) { 
      Log.d("downloading url", e.toString()) 
     } finally { 
      if (iStream != null) iStream.close() 
      if (urlConnection != null) urlConnection.disconnect() 
     } 
     return data 
    } 

companion object { 
    ... 
    var placesTask: PlacesTask? = null 
    var setPlacesTask: SetPlaceTask? = null 

    class PlacesTask(mainActivity: MainActivity) : AsyncTask<String, Int, String>() { 
      private val mRef: WeakReference<MainActivity> = WeakReference(mainActivity) 

      override fun doInBackground(vararg url: String): String? { 
       var data: String? = null 
       try { 
        data = mRef.get()?.downloadUrl(url[0]) 
       } catch (e: Exception) { 
        Log.d("Background Task", e.toString()) 
       } 
       return data 
      } 

      override fun onPostExecute(result: String) { 
       setPlacesTask = SetPlaceTask(mRef.get()!!).execute(result) as SetPlaceTask? 
      } 
     } 

     class SetPlaceTask(mainActivity: MainActivity) : AsyncTask<String, Int, List<HashMap<String, String>>>() { 
      private val mRef: WeakReference<MainActivity> = WeakReference(mainActivity) 

      override fun doInBackground(vararg jsonData: String): List<HashMap<String, String>>? { 
       var places: List<HashMap<String, String>>? = null 
       try { 
        places = PlaceJSONParser().parse(JSONObject(jsonData[0])) 
       } catch (e: Exception) { 
        Log.d("Exception", e.toString()) 
       } 
       return places 
      } 

      override fun onPostExecute(list: List<HashMap<String, String>>) { 
       for (i in list.indices) { 
        val hmPlace = list[i] 
        mRef.get()?.parkingLatLng = LatLng(hmPlace["lat"]!!.toDouble(), hmPlace["lng"]!!.toDouble()) 
        mRef.get()?.mMarkerPlaceLink!!.put(mRef.get()?.map!!.addMarker(MarkerOptions().icon(mRef.get()?.vectorToBitmap(R.drawable.ic_local_parking_black_12dp, ContextCompat.getColor(mRef.get()?.applicationContext, R.color.colorPrimaryDark))).position(mRef.get()?.parkingLatLng!!).title(hmPlace["place_name"] + "\n" + hmPlace["vicinity"])).id, hmPlace["reference"].toString()) 
        mRef.get()?.map!!.addCircle(CircleOptions().center(mRef.get()?.parkingLatLng).radius(1.0).strokeColor(Color.BLACK).fillColor(Color.WHITE).strokeWidth(1f).zIndex(1f)) 
       } 
      } 
     } 
} 

コール:placesTask = PlacesTask(this).execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="...) as PlacesTask?

幸運!

2

例外として、パラメータresultnullですが、nullを許可しないと定義しています。

そのパラメータがdoInBackgroundによって返される値であるのでdownloadUrlnullとしてdata変数を残して、例外をスローしたので、それが起こります。例外が発生したときに

  1. doInBackgroundがnullを返すことはありませんことを確認し、null以外のデフォルトの戻り値を定義します。

    それを修正するには、これらのオプションのいずれかを行います。

  2. onPostExecuteのパラメータタイプをString?に変更し、例外が発生したときにnullになる可能性のあるケースを処理します。
関連する問題