Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Edistynyt mobiiliohjelmointi, 3.2.2023
- // data haetaan osoitteesta:
- // https://jsonplaceholder.typicode.com/comments
- // CommentApiFragment -pohja:
- class CommentApiFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentCommentApiBinding? = 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 = FragmentCommentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // the binding -object allows you to access views in the layout, textviews etc.
- return root
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
- // muokataan CommentFragmentApin ulkoasua (xml)
- <?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=".CommentApiFragment">
- <Button
- android:id="@+id/button_get_comments"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="Get data" />
- </LinearLayout>
- // CommentApiFragment, ladataan data Volleylla
- package com.example.edistynytmobiiliohjelmointi2023b
- import android.os.Bundle
- import android.util.Log
- import androidx.fragment.app.Fragment
- import android.view.LayoutInflater
- import android.view.View
- import android.view.ViewGroup
- import androidx.navigation.findNavController
- import com.android.volley.AuthFailureError
- import com.android.volley.Request
- import com.android.volley.Response
- import com.android.volley.toolbox.StringRequest
- import com.android.volley.toolbox.Volley
- import com.example.edistynytmobiiliohjelmointi2023b.databinding.FragmentCommentApiBinding
- import com.example.edistynytmobiiliohjelmointi2023b.databinding.FragmentDataReadBinding
- class CommentApiFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentCommentApiBinding? = 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 = FragmentCommentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- binding.buttonGetComments.setOnClickListener {
- Log.d("TESTI", "Nappi toimii!")
- // haetaan kommentit rajapinnasta
- getComments()
- }
- // the binding -object allows you to access views in the layout, textviews etc.
- return root
- }
- // apunfunktio, joka hakee Volleylla dataa fragmenttiin
- 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
- }
- }
- // GSONia varten tarvitaan data class, joka esittää yksittäistä kommenttidataa. tässä voi käyttää
- // json2kt.com -palvelua. esim.
- 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
- )
- // Muutetaan GSONilla raaka JSON-data Kotlin-dataksi
- class CommentApiFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentCommentApiBinding? = 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 = FragmentCommentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- binding.buttonGetComments.setOnClickListener {
- Log.d("TESTI", "Nappi toimii!")
- // haetaan kommentit rajapinnasta
- getComments()
- }
- // the binding -object allows you to access views in the layout, textviews etc.
- return root
- }
- // apunfunktio, joka hakee Volleylla dataa fragmenttiin
- fun getComments()
- {
- // this is the url where we want to get our data from
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // alustetaan GSON-plugin
- 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 ->
- // print the response as a whole
- // we can use GSON to modify this response into something more usable
- // Log.d("ADVTECH", response)
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- 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)
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
- // RecyclerView tarvitsee oman ulkoasu-xml:n jokaista kommenttia varten (eli miltä yksittäinen kommentti listassa näyttää)
- <?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="#AB4CC5"
- 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="#3EA8BC"
- 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>
- // CommentAdapter
- package com.example.edistynytmobiiliohjelmointi2023b
- import android.view.LayoutInflater
- import android.view.View
- import android.view.ViewGroup
- import androidx.recyclerview.widget.RecyclerView
- import com.example.edistynytmobiiliohjelmointi2023b.databinding.RecyclerviewItemRowBinding
- // aloitetaan luomalla uusi luokka CommentHolder
- class CommentAdapter(private val comments: List<Comment>) : RecyclerView.Adapter<CommentAdapter.CommentHolder>() {
- // tähän väliin tulee kaikki RecyclerView-adapterin vaatimat metodit
- // kuten onCreateViewHolder, onBindViewHolder sekä getItemCount
- // 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)
- {
- this.comment = comment
- // asetetaan oikeat datat oikeaan kohtaan
- // ulkoasussa
- view.textViewCommentEmail.text = comment.email.toString()
- view.textViewCommentName.text = comment.name.toString()
- view.textViewCommentBody.text = comment.body.toString()
- }
- // jos itemiä klikataan käyttöliittymässä, ajetaan tämä koodio
- override fun onClick(v: View) {
- }
- }
- }
- // lisätään RecyclerView fragmentin ulkoasuun (CommentApiFragment)
- <?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=".CommentApiFragment">
- <Button
- android:id="@+id/button_get_comments"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="10dp"
- android:text="Get data" />
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/recyclerView_comments"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- </androidx.recyclerview.widget.RecyclerView>
- </LinearLayout>
- // CommentApiFragment, kytketään adapteri recyclerviewiin:
- class CommentApiFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentCommentApiBinding? = 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 = FragmentCommentApiBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // asetetaan RecyclerViewille linear layout manager
- linearLayoutManager = LinearLayoutManager(context)
- binding.recyclerViewComments.layoutManager = linearLayoutManager
- binding.buttonGetComments.setOnClickListener {
- Log.d("TESTI", "Nappi toimii!")
- // haetaan kommentit rajapinnasta
- getComments()
- }
- // the binding -object allows you to access views in the layout, textviews etc.
- return root
- }
- // apunfunktio, joka hakee Volleylla dataa fragmenttiin
- fun getComments()
- {
- // this is the url where we want to get our data from
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // alustetaan GSON-plugin
- 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 ->
- // print the response as a whole
- // we can use GSON to modify this response into something more usable
- // Log.d("ADVTECH", response)
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- for(item in rows)
- {
- Log.d("ADVTECH", item.email.toString())
- }
- // kytketään rajapinnasta ladattu data recyclerviewin adapteriin
- 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
- }
- }
- // Com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement