Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Edistynyt mobiiliohjelmointi, 1.2.2023, luentomuistiinpanot
- ApiFragment, 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="GET COMMENTS" />
- </LinearLayout>
- // Comment-API
- // JSON URL = https://jsonplaceholder.typicode.com/comments
- // muista lisätä dependencyt ja permissionit manifestiin, ks. Moodle
- // ApiFragment:
- class ApiFragment : Fragment() {
- private var _binding: FragmentApiBinding? = null
- // This property is only valid between onCreateView and
- // onDestroyView.
- private val binding get() = _binding!!
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- _binding = FragmentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // print out the given parameter into logs
- // haetaan dataa omalla funktiolla kun nappia painetaan
- binding.buttonGetComments.setOnClickListener {
- getComments()
- }
- return root
- }
- fun getComments()
- {
- // this is the url where we want to get our data from
- 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)
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
- // Tarvitaan kommenttidatalle oma dataluokka, esim. Comment.kt:
- // tämän voi generoida json2kt.com -työkalulla
- import com.google.gson.annotations.SerializedName
- data class Comment (
- @SerializedName("postId" ) var postId : Int? = null,
- @SerializedName("id" ) var id : Int? = null,
- @SerializedName("name" ) var name : String? = null,
- @SerializedName("email" ) var email : String? = null,
- @SerializedName("body" ) var body : String? = null
- )
- // GSONin avulla JSON voidaan muuttaa Kotlin-muotoon
- fun getComments()
- {
- // this is the url where we want to get our data from
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // alustetaan GSON
- val gson = GsonBuilder().setPrettyPrinting().create()
- // Request a string response from the provided URL.
- val stringRequest: StringRequest = object : StringRequest(
- Request.Method.GET, JSON_URL,
- Response.Listener { response ->
- // muutetaan raaka-JSON rajapinnasta (response) GSONin avulla listaksi Comment-objekteja
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- // tulostetaan silmukassa jokaisen kommentin email-osoite
- for(item in rows)
- {
- Log.d("ADVTECH", item.email.toString())
- }
- },
- 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)
- }
- // RecyclerViewiä varten tarvitaan oma xml-tiedosto, joka esittää YKSITTÄISTÄ kommenttia listassa
- <?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="140dp">
- <TextView
- android:id="@+id/textView_comment_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="Kommentin name"
- android:textColor="#619526"
- android:textStyle="bold"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- <TextView
- android:id="@+id/textView_comment_email"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="Kommentin email"
- android:textColor="#6A33DA"
- android:textStyle="bold|italic"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- <TextView
- android:id="@+id/textView_comment_body"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="Kommentin body"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toBottomOf="@+id/textView_comment_name" />
- </androidx.constraintlayout.widget.ConstraintLayout>
- // RecyclerView vaatii aina adapterin, jossa oma data kytketään omaan ulkoasuun
- class CommentAdapter(private val comments: List<Comment>) : RecyclerView.Adapter<CommentAdapter.CommentHolder>() {
- // binding layerin muuttujien alustaminen
- private var _binding: RecyclerviewItemRowBinding? = null
- private val binding get() = _binding!!
- // ViewHolderin onCreate-metodi. käytännössä tässä kytketään binding layer
- // osaksi CommentHolder-luokkaan (adapterin sisäinen luokka)
- // koska CommentAdapter pohjautuu RecyclerViewin perusadapteriin, täytyy tästä
- // luokasta löytyä metodi nimeltä onCreateViewHolder
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommentHolder {
- // binding layerina toimii yksitätinen recyclerview_item_row.xml -instanssi
- _binding = RecyclerviewItemRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
- return CommentHolder(binding)
- }
- // tämä metodi kytkee yksittäisen Comment-objektin yksittäisen CommentHolder-instanssiin
- // koska CommentAdapter pohjautuu RecyclerViewin perusadapteriin, täytyy tästä
- // luokasta löytyä metodi nimeltä onBindViewHolder
- override fun onBindViewHolder(holder: CommentHolder, position: Int) {
- val itemComment = comments[position]
- holder.bindComment(itemComment)
- }
- // Adapterin täytyy pysty tietämään sisältämänsä datan koko tämän metodin avulla
- // koska CommentAdapter pohjautuu RecyclerViewin perusadapteriin, täytyy tästä
- // luokasta löytyä metodi nimeltä getItemCount
- override fun getItemCount(): Int {
- return comments.size
- }
- // CommentHolder, joka määritettiin oman CommentAdapterin perusmäärityksessä (ks. luokan yläosa)
- // Holder-luokka sisältää logiikan, jolla data ja ulkoasu kytketään toisiinsa
- class CommentHolder(v: RecyclerviewItemRowBinding) : RecyclerView.ViewHolder(v.root), View.OnClickListener {
- // tämän kommentin ulkoasu ja varsinainen data
- private var view: RecyclerviewItemRowBinding = v
- private var comment: Comment? = null
- // mahdollistetaan yksittäisen itemin klikkaaminen tässä luokassa
- init {
- v.root.setOnClickListener(this)
- }
- // metodi, joka kytkee datan yksityiskohdat ulkoasun yksityiskohtiin
- fun bindComment(comment : Comment)
- {
- // otetaan kommentti talteen ylätasolle, että voimme käyttää sitä myös esim. onClickissä
- this.comment = comment
- view.textViewCommentName.text = comment.name
- view.textViewCommentEmail.text = comment.email
- view.textViewCommentBody.text = comment.body
- }
- // jos itemiä klikataan käyttöliittymässä, ajetaan tämä koodio
- override fun onClick(v: View) {
- Log.d("ADVTECH", "RecyclerView CLICK!!!")
- }
- }
- }
- // lisätään ApiFragmentin ulkoasuun myös RecyclerView (huomaa recyclerviewin id myös)
- <?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="GET COMMENTS" />
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/recyclerView_comments"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
- </LinearLayout>
- // tehdään loput kytkennät recyclerviewiin fragmentissa
- class ApiFragment : Fragment() {
- private var _binding: FragmentApiBinding? = null
- // alustetaan viittaus adapteriin sekä luodaan LinearLayoutManager
- // RecyclerView tarvitsee jonkin LayoutManagerin, joista yksinkertaisin on Linear
- private lateinit var adapter: CommentAdapter
- private lateinit var linearLayoutManager: LinearLayoutManager
- // This property is only valid between onCreateView and
- // onDestroyView.
- private val binding get() = _binding!!
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- _binding = FragmentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // luodaan layout manager ja kytketään se ulkoasun recyclerviewiin
- linearLayoutManager = LinearLayoutManager(context)
- binding.recyclerViewComments.layoutManager = linearLayoutManager
- // haetaan dataa omalla funktiolla kun nappia painetaan
- binding.buttonGetComments.setOnClickListener {
- getComments()
- }
- return root
- }
- fun getComments()
- {
- // this is the url where we want to get our data from
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // alustetaan GSON
- val gson = GsonBuilder().setPrettyPrinting().create()
- // Request a string response from the provided URL.
- val stringRequest: StringRequest = object : StringRequest(
- Request.Method.GET, JSON_URL,
- Response.Listener { response ->
- // muutetaan raaka-JSON rajapinnasta (response) GSONin avulla listaksi Comment-objekteja
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- // tulostetaan silmukassa jokaisen kommentin email-osoite
- for(item in rows)
- {
- Log.d("ADVTECH", item.email.toString())
- }
- // luodaan adapteri datan kanssa ja kytketään se recycler viewiin
- adapter = CommentAdapter(rows)
- binding.recyclerViewComments.adapter = adapter
- },
- 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)
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement