0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AsyncTaskのジェネリスク型パラメータメモ

Posted at

AsyncTaskとは

メインスレッドとは別のスレッドで処理できる非同期処理の手段
型忘れちゃうのでメモします
xmlでの表示はListView、SimpleAdapterで適当に出してます

MainActivity.kt

//~~~~~~~省略~~~~~~~~~~~~
    private inner class ListItemClickListener: AdapterView.OnItemClickListener{
        override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            //タップされたIDを取得
            val item = parent?.getItemAtPosition(position) as Map<String,String>
            val Name = item["name"]
            val Id = item["id"]

            val receiver = Receiver()
            //実行
            receiver.execute(Id) //★第一引数!実行するID
        }
    }

private inner class Receiver(): AsyncTask<String,String,String>() {
        override fun doInBackground(vararg params: String?): String { //★第三引数!doInBackground()の戻り値。この場合はresult
            val id = params[0]
            val urlStr = "http://APIのURL/json/v1?city=${id}"

            //~~~文字列で返す処理(省略)~~~~

            return result
        }

        override fun onPostExecute(result: String?) {
           
            //~~~文字列を解析する処理(省略)~~~

            //情報用文字列をセット
            val tvTelop = findViewById<TextView>(R.id.tvTelop)
            val tvDesc = findViewById<TextView>(R.id.tvDesc)
            tvTelop.text = telop
            tvDesc.text = desc
        }
    }

AsyncTask()の型についてメモ

  • 一つ目の引数はReceiver()を実行するときのexecute()の引数。この場合はId
    val id = params[0]に使われている。

  • 二つ目の引数はpublishProgress()実行時に渡された引数

  • 三つ目の引数はdoInBackground()の戻り値およびonPostExecute()の引数の型
    この場合はreturn result および onPostExecute(result: String?)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?