Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Edistynyt mobiiliohjelmointi, luento, 16.1.2023
- JSON comments data:
- https://jsonplaceholder.typicode.com/comments
- ApiFragmentin ulkoasu:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context=".ApiFragment">
- <Button
- android:id="@+id/button_get_comments"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Button" />
- </LinearLayout>
- ApiFragment.kt
- onCreateViewiin ->
- binding.buttonGetComments.setOnClickListener{
- getComments()
- }
- ja uusi oma funktio:
- fun getComments()
- {
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // Request a string response from the provided URL.
- val stringRequest: StringRequest = object : StringRequest(
- Request.Method.GET, JSON_URL,
- Response.Listener { response ->
- // print the response as a whole
- // we can use GSON to modify this response into something more usable
- Log.d("ADVTECH", response)
- },
- Response.ErrorListener {
- // typically this is a connection error
- Log.d("ADVTECH", it.toString())
- })
- {
- @Throws(AuthFailureError::class)
- override fun getHeaders(): Map<String, String> {
- // basic headers for the data
- val headers = HashMap<String, String>()
- headers["Accept"] = "application/json"
- headers["Content-Type"] = "application/json; charset=utf-8"
- return headers
- }
- }
- // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
- // if using this in an activity, use "this" instead of "context"
- val requestQueue = Volley.newRequestQueue(context)
- requestQueue.add(stringRequest)
- }
- Työkalu: https://json2kt.com/
- Laita yksittäisen JSON-objektin data pelkästään
- Kopioi Comment.kt -tiedosto projektiisi, ja käytä sitä Response.Listenerissä:
- val gson = GsonBuilder().setPrettyPrinting().create()
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- for(item: Comment in rows)
- {
- Log.d("ADVTECH", item.email.toString())
- }
- RecyclerView-tutorial, jota käytetään pohjana:
- https://www.raywenderlich.com/1560485-android-recyclerview-tutorial-with-kotlin
- Lisätään RecyclerView ulkoasuun:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- tools:context=".ApiFragment">
- <Button
- android:id="@+id/button_get_comments"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Button" />
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/recyclerView_comments"
- android:layout_width="match_parent"
- android:layout_height="500dp" />
- </LinearLayout>
- Fragmentissa, lisää funktioiden ulkopuolelle:
- // alustetaan layout manager recyclerviewille
- private lateinit var linearLayoutManager: LinearLayoutManager
- Fragmentissa, onCreateViewin sisälle:
- // luodaan layout manager ja kytketään se recyclerviewiin ulkoasussa
- // huom, koska käytämme fragmentia, this-sanan sijasta käytetään -> context
- linearLayoutManager = LinearLayoutManager(context)
- binding.recyclerViewComments.layoutManager = linearLayoutManager
- Tehdään yksittäiselle kommentille oma layout xml, esim.
- <?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="160dp">
- <TextView
- android:id="@+id/textView_comment_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="20dp"
- android:text="Nimi"
- android:textColor="#3F51B5"
- android:textStyle="bold"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- <TextView
- android:id="@+id/textView_comment_content"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="20dp"
- android:text="Sisältö"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/textView_comment_name" />
- <TextView
- android:id="@+id/textView_comment_email"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="20dp"
- android:text="email"
- android:textColor="#8BC34A"
- android:textStyle="bold|italic"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- </androidx.constraintlayout.widget.ConstraintLayout>
- // RECYCLER ADAPTER, VERSIO 1
- package com.example.android2023tv
- import android.util.Log
- import android.view.LayoutInflater
- import android.view.View
- import android.view.ViewGroup
- import androidx.recyclerview.widget.RecyclerView
- import com.example.android2023tv.databinding.RecyclerviewItemRowBinding
- class RecyclerAdapter(private val comments: List<Comment>) :
- RecyclerView.Adapter<RecyclerAdapter.CommentHolder>() {
- // alustetaan binding layet -> recyclerview_item_row.xml
- private var _binding: RecyclerviewItemRowBinding? = null
- private val binding get() = _binding!!
- // RecyclerAdapter vaatii, että luokassa on toteutettuna:
- // getItemCount, onCreateViewHolder, OnBindViewHolder
- // jotta RecyclerView tietää kuinka monta itemiä listassa on
- override fun getItemCount() = comments.size
- // tämä funktio kytkee jokaisen yksittäisen datan listassa omaan ulkoasuunsa
- // (recyclerview_item_row.xml)
- override fun onBindViewHolder(holder: RecyclerAdapter.CommentHolder, position: Int) {
- val itemComment = comments[position]
- holder.bindComment(itemComment)
- }
- // luodaan binding layer ja kytketään se CommentHolderiin
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.CommentHolder {
- _binding = RecyclerviewItemRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
- return CommentHolder(binding)
- }
- // CommentHolder kytkee datan ulkoasuun jokaisen itemin kohdalla
- class CommentHolder(v: RecyclerviewItemRowBinding) : RecyclerView.ViewHolder(v.root), View.OnClickListener {
- // view => binding layer
- // comment => yksittäinen comment-data
- private var view: RecyclerviewItemRowBinding = v
- private var comment: Comment? = null
- // v.root tarvitaan siksi, koska v on tässä tapauksessa binding layer, ei View
- // v.root on binding layerin pohjimmainen View, eli ulkoasu
- init {
- v.root.setOnClickListener(this)
- }
- // tätä fuktiota kutsutaan jokaisen comment-datan kohdalla
- // kun se asetetaan listaan
- // toisin sanoen, tässä funktiossa päätetään mikä muuttuja
- // kytketään mihinkiin Viewiin, esim. TextViewiin
- fun bindComment(comment: Comment)
- {
- }
- override fun onClick(v: View) {
- Log.d("RecyclerView", "CLICK!")
- }
- }
- }
- // bindCommentissa määritetään mikä data menee mihinkin TextViewiin, esim.
- fun bindComment(comment: Comment)
- {
- view.textViewCommentName.text = comment.name
- view.textViewCommentContent.text = comment.body
- view.textViewCommentEmail.text = comment.email
- }
- // Fragmentissa, lisätään adapteri funktioiden ulkopuolelle:
- private lateinit var adapter: RecyclerAdapter
- // Response.Listenerissä, jos rows-muuttujassa on lista kommenteista, silloin:
- adapter = RecyclerAdapter(rows)
- binding.recyclerViewComments.adapter = adapter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement