본문 바로가기
안드로이드

[android][kotlin] Json과 RecyclerView

by 코드 이야기 2021. 2. 17.
728x90

 

 

Json으로 값을 받아와 RecyclerView와 CardView를 이용해 각 객체들을 나열해보겠습니다.

json과 gson에 대한 설명은 이 블로그에 잘 정리가 되어있더군요.

 

 

 

앱에서 인터넷을 사용할 것이기때문에 Menifest에 권한을 포함해주어야합니다.

아래의 코드 두 줄을 Menifest에 추가해줍시다.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

 

직렬화되어 전달된 json을 java객체로 전환시켜주는 gson라이브러리를 사용하기위해 gradle에 아래의 코드를 추가해줍시다.

implementation 'com.google.code.gson:gson:2.8.6'

 

 

 

화면부터 꾸며주고

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/personRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="LinearLayoutManager"/>

</LinearLayout>

 

 

정보들을 이쁘게 담아줄 카드뷰를 만들어줍시다.

item_person.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/personCardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    app:cardBackgroundColor="#E2FCFF"
    app:cardCornerRadius="7dp"
    app:contentPadding="15dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:orientation="vertical">
            <TextView
                android:id="@+id/id_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="id: " />
            <TextView
                android:id="@+id/name_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name: " />
            <TextView
                android:id="@+id/age_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="age: " />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <TextView
                android:id="@+id/intro_tv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center|left"
                android:text="intro" />
        </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

 

 

 

 

Json으로 받아온걸 직렬화해서 클래스로 가지고있어줍시다.

Person.kt

package com.example.myapplication

import java.io.Serializable

class Person(
    var id: Int? = null,
    var name: String? = null,
    var age: Int? = null,
    var intro: String? = null
) : Serializable

 

 


가져온 정보를 RecyclerView에 붙여줍시다.

PersonListAdapter.kt

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.Person
import com.example.myapplication.R

class PersonListAdapter(
        val personList: Array<Person>,
        val inflater: LayoutInflater
) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val id: TextView
        val name: TextView
        val age: TextView
        val intro: TextView

        init {
            id = itemView.findViewById(R.id.id_tv)
            name = itemView.findViewById(R.id.name_tv)
            age = itemView.findViewById(R.id.age_tv)
            intro = itemView.findViewById(R.id.intro_tv)
        }
    }

    override fun getItemCount(): Int {
        return personList.size
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.id.setText(personList.get(position).id.toString() ?: "")
        holder.name.setText(personList.get(position).name ?: "")
        holder.age.setText(personList.get(position).age.toString())
        holder.intro.setText(personList.get(position).intro ?: "")
    }
}

 

 

 

MainThread에서는 네트워크와 연결하면 안되기때문에 NetworkTask를 만들어줍시다.

NetworkTask.kt

package com.example.myapplication

import PersonListAdapter
import android.os.AsyncTask
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

class NetworkTask(
        val listView: RecyclerView,
        val inflater: LayoutInflater
): AsyncTask<Any?, Any?, Array<Person>>() {
    
    override fun onPostExecute(result: Array<Person>?) {
        val adapter = PersonListAdapter(result!!, inflater)
        listView.adapter = adapter
        super.onPostExecute(result)
    }

    override fun doInBackground(vararg params: Any?): Array<Person>? {
        val urlString: String = "[인터넷 주소]"
        val url: URL = URL(urlString)
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection

        connection.requestMethod = "GET"
        connection.setRequestProperty("Content-Type", "application/json")

        var buffer = ""
        if (connection.responseCode == HttpURLConnection.HTTP_OK) {
            val reader = BufferedReader(
                    InputStreamReader(
                            connection.inputStream,
                            "UTF-8"
                    )
            )
            buffer = reader.readLine()
        }
        val data = Gson().fromJson(buffer, Array<Person>::class.java)
        return data
    }
}

 

 

 

MainActivity.kt

 

 

 

 

 

 

 

 

 

 

 

 

728x90

댓글