Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- JS
- array
- 안드로이드
- Kotlin
- stylesheet
- 코틀린
- scrollview
- TextView
- TypeScript
- Hook
- React
- 스프링부트
- nodejs
- RecyclerView
- 랜덤번호
- npm
- Javscript
- Linux
- button
- 리액트
- 랜덤넘버
- Android
- 오버라이딩
- 자바스크립트
- JavaScript
- 구글맵스
- Java
- GoogleMaps
- fragment
- SpringBoot
Archives
- Today
- Total
타닥타닥 개발자의 일상
Kotlin 코틀린 JSON 이용하여 안드로이드 화면에 전송한 자료 출력하기 본문
폴더 구성 및 파일 구성
main 폴더 우클릭> 새로 만들기 >경로 > assets 폴더 생성
assets 폴더 우클릭 > 새로 만들기 > 파일 > data.json 파일 생성
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="424dp"
android:layout_height="466dp"
android:text=""
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
data.json
[
{
"id": "kotlin",
"language": "코틀린"
},
{
"id": "java",
"language": "자바"
},
{
"id": "swift",
"language": "스위프트"
}
]
MainActivity.kt
package com.example.sample32
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import org.json.JSONArray
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//문자열
val jsonStr = assets.open("data.json").reader().readText()
//assets폴더에서 data.json이라는 파일을 찾아 일고 jsonStr이라는 변수에 저장
Log.d("jsonStr",jsonStr)
//Json
val jsonArray = JSONArray(jsonStr)
//data.json 파일에서 읽어온 값을 jasonArray라는 배열 변수에 넣는다.
Log.d("jsonStr",jsonArray.toString())
val textView = findViewById<TextView>(R.id.textView)
for (i in 0 until jsonArray.length()){
val jsonObject = jsonArray.getJSONObject(i)
//jsonObject라는 변수는 데이터 값이 저장되어있는 jasonArray의 각 i번째 값이다.
textView.append("\n--------------------------------\n")
val id = jsonObject.getString("id") 데이터 값에서 id값을 불러온다
val language = jsonObject.getString("language") 데이터 값에서 language 값을 불러온다
textView.append(
"""
$id
""".trimIndent()
)
//textView에 id 값을 출력한다
textView.append(
"""
$language
""".trimIndent()
//textView에 language 값을 출력한다
)
}
}
}
실행화면
'코딩 기록 > Kotlin' 카테고리의 다른 글
Comments