[안드로이드] 네트워크-Async2

나고수·2021년 9월 6일
0

andriod

목록 보기
3/27
post-thumbnail
post-custom-banner

Async와 HttpUrlConnection으로 데이터 받아서 recyclerview에 뿌리기 실습

//NetWork1Activity.kt

class NetWork1Activity : AppCompatActivity() {
    private lateinit var binding: ActivityNetWork1Binding
    val url = URL("https://jsonplaceholder.typicode.com/posts")
    val connection: HttpURLConnection = url.openConnection() as HttpURLConnection

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNetWork1Binding.inflate(layoutInflater)
        setContentView(binding.root)

        BackgroundAsyncTask2(
            connection,
            LayoutInflater.from(this@NetWork1Activity),
            binding,
            this@NetWork1Activity
        ).execute()
    }


}

//메인쓰레드는 멈출 수 없으므로 메인쓰레드에서 네트워크 통신 불가. 따라서 async 비동기방식으로 진행
class BackgroundAsyncTask2(
    var connection: HttpURLConnection,
    val inflater: LayoutInflater,
    val binding: ActivityNetWork1Binding,
    val context: Context
) : AsyncTask<Any?, Any?, Array<Person>>() {
    //params -> doInBackground에서 사용 할 타입
    //progress -> onProgressUpdate에서 사용할 타입
    //result -> onPostExecute에서 사용할 타입
    var data: Array<Person>? = null

    //실행하기 바로 직전
    override fun onPreExecute() {

    }

    override fun doInBackground(vararg params: Any?): Array<Person> {


        //get방식으로 요청
        connection.requestMethod = "GET"
        //header을 쓴 것임. json타입으로 요청하겠다.
        connection.setRequestProperty("Content_Type", "application/json")
        var buffer = ""
        //통신이 제대로 되면
        if (connection.responseCode == HttpURLConnection.HTTP_OK) {
            Log.d("connn", "inputstream" + connection.inputStream)
            //inputstreamreader을 뭉태기로 읽어서 reader에 저장한다
            val reader = BufferedReader(
                //서버와 클라이언트가 통신할 때는 byte로 된 사람이 읽을 수 없는 byte들이 왔다갔다하는데, 이것이 Inputstreamd이다.
                //그것(byte==inputstream)을 utf-8로 읽을거야 라고 말하는것이 inputstreamreader
                InputStreamReader(
                    connection.inputStream,
                    "UTF-8"
                )
            )
            //reader을 읽어온다.
            buffer = reader.readText()
            Log.d("connn", "buffer" + buffer)


            //response가 array일경우, buffer에 있는 것을 array로 받는다.
            data = Gson().fromJson(buffer, Array<Person>::class.java)
            Log.d("connn", "data" + data!![0].title)
        }

        return data!!
    }

    override fun onProgressUpdate(vararg values: Any?) {

    }

    //UI쓰레드에 접근 가능
    override fun onPostExecute(result: Array<Person>) {
        val adatper = NetworkAdapter(data!!, inflater)
        binding.recyclerNet.adapter = adatper
        binding.recyclerNet.layoutManager = LinearLayoutManager(context)

    }

    override fun onCancelled() {

    }

}
//NetWork1Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NetWork1Activity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_net"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>```

```kotlin
//NetworkAdapter.kt

class NetworkAdapter(val itemList: Array<Person>, val inflater: LayoutInflater) :
    RecyclerView.Adapter<NetworkAdapter.ViewHolder>() {
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var userId: TextView? = null
        var id: TextView? = null
        var title: TextView? = null
        var body: TextView? = null

        init {
            userId = itemView.findViewById<TextView>(R.id.userId)
            id = itemView.findViewById<TextView>(R.id.id)
            title = itemView.findViewById<TextView>(R.id.title)
            body = itemView.findViewById<TextView>(R.id.body)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val viewHolder = inflater.inflate(R.layout.network_list, parent, false)
        return ViewHolder(viewHolder)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.userId!!.text = itemList[position].userId.toString()
        // holder.id!!.text = itemList[position].id.toString()
        holder.title!!.text = itemList[position].title.toString()
        holder.body!!.text = itemList[position].body.toString()
    }

    override fun getItemCount(): Int {
        return itemList.size
    }
}
//list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="#DD6767"
    android:orientation="vertical">

    <TextView
        android:id="@+id/userId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

profile
되고싶다
post-custom-banner

0개의 댓글