Advertisement
tuomasvaltanen

Untitled

Mar 27th, 2023 (edited)
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.58 KB | None | 0 0
  1. // Edistynyt mobiiliohjelmointi, 27.3.2023
  2.  
  3. // haetaan yksittäinen Comment-data rajapinnasta, esim:
  4.  
  5. https://jsonplaceholder.typicode.com/comments/1
  6.  
  7. Käytetään json2kt.com palvelua ja generoidaan dataluokka:
  8.  
  9. package com.example.OMANPROJEKTINPAKETTITÄHÄN
  10.  
  11. import com.google.gson.annotations.SerializedName
  12.  
  13. data class Comment (
  14.  
  15. @SerializedName("postId" ) var postId : Int? = null,
  16. @SerializedName("id" ) var id : Int? = null,
  17. @SerializedName("name" ) var name : String? = null,
  18. @SerializedName("email" ) var email : String? = null,
  19. @SerializedName("body" ) var body : String? = null
  20.  
  21. )
  22.  
  23. // GSON ja Volley, tarvitaan importitit. Gradle Scripts -> build.gradle (Module:app):
  24.  
  25. // dependencies -lohkon sisälle jatkoksi:
  26.  
  27. implementation 'com.android.volley:volley:1.2.1'
  28. implementation 'com.google.code.gson:gson:2.10.1'
  29.  
  30. // lisätään myös AndroidManifestiin permissionit:
  31.  
  32. <uses-permission android:name="android.permission.INTERNET" />
  33. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  34.  
  35. Huom: koska Android ei päivitä manifestin permissioneja enää asennuksen jälkeen,
  36. Volley -koodi ei enää toimi tällä asennuksella koska se ei saa yhteyttä internetiin.
  37.  
  38. Tässä vaiheessa emulaattori kiinni -> kolmen pisteen valikko -> Wipe Data (device manager)
  39.  
  40. #########################################################################
  41. TEE UUSI FRAGMENT mobile_navigation -työkalun avulla: CommentDataFragment
  42. #########################################################################
  43.  
  44. Lisätään CommentDataFragment päävalikkkoon (res -> menu -> activity_main_drawer.xml)
  45.  
  46. Lisätään myös MainActivityn appBarConfigurationin listaan fragment, esim:
  47.  
  48. appBarConfiguration = AppBarConfiguration(
  49. setOf(
  50. R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.dataFragment,
  51. R.id.commentDataFragment
  52. ), drawerLayout
  53. )
  54.  
  55. // otetaan binding layer käyttöön CommentDataFragmentissa
  56. class CommentDataFragment : Fragment() {
  57. private var _binding: FragmentCommentDataBinding? = null
  58. // This property is only valid between onCreateView and
  59. // onDestroyView.
  60. private val binding get() = _binding!!
  61. override fun onCreateView(
  62. inflater: LayoutInflater,
  63. container: ViewGroup?,
  64. savedInstanceState: Bundle?
  65. ): View? {
  66. _binding = FragmentCommentDataBinding.inflate(inflater, container, false)
  67. val root: View = binding.root
  68.  
  69.  
  70. return root
  71. }
  72. override fun onDestroyView() {
  73. super.onDestroyView()
  74. _binding = null
  75. }
  76. }
  77.  
  78. // muutetaan ulkoasuksi LinearLayout ja lisätään nappi jolla haetaan dataa
  79.  
  80. <?xml version="1.0" encoding="utf-8"?>
  81. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  82. xmlns:tools="http://schemas.android.com/tools"
  83. android:layout_width="match_parent"
  84. android:layout_height="match_parent"
  85. android:orientation="vertical"
  86. tools:context=".CommentDataFragment">
  87.  
  88. <Button
  89. android:id="@+id/button_get_comments"
  90. android:layout_width="match_parent"
  91. android:layout_height="wrap_content"
  92. android:text="GET DATA" />
  93.  
  94. </LinearLayout>
  95.  
  96. // tehdään apufunktio/metodi, johon voidaan keskittää Volley-koodi, eli raakadatan lataaminen
  97.  
  98. override fun onCreateView(
  99. inflater: LayoutInflater,
  100. container: ViewGroup?,
  101. savedInstanceState: Bundle?
  102. ): View? {
  103. _binding = FragmentCommentDataBinding.inflate(inflater, container, false)
  104. val root: View = binding.root
  105.  
  106. // haetaan dataa kun nappia painetaan
  107. binding.buttonGetComments.setOnClickListener {
  108. getComments()
  109. }
  110.  
  111. return root
  112. }
  113.  
  114. // apufunktio/metodi, joka hakee dataa rajapinnasta
  115. fun getComments() {
  116. Log.d("TESTI", "getComments() kutsuttu")
  117. }
  118.  
  119.  
  120. // haetaan Volleylla dataa, muista tyhjentää emulaattori, jotta permissionit päivittyy, muuten tulee NoConnectionError
  121.  
  122. class CommentDataFragment : Fragment() {
  123. private var _binding: FragmentCommentDataBinding? = null
  124.  
  125. // This property is only valid between onCreateView and
  126. // onDestroyView.
  127. private val binding get() = _binding!!
  128.  
  129. override fun onCreateView(
  130. inflater: LayoutInflater,
  131. container: ViewGroup?,
  132. savedInstanceState: Bundle?
  133. ): View? {
  134. _binding = FragmentCommentDataBinding.inflate(inflater, container, false)
  135. val root: View = binding.root
  136.  
  137. // haetaan dataa kun nappia painetaan
  138. binding.buttonGetComments.setOnClickListener {
  139. getComments()
  140. }
  141.  
  142. return root
  143. }
  144.  
  145. // apufunktio/metodi, joka hakee dataa rajapinnasta
  146. fun getComments() {
  147. Log.d("TESTI", "getComments() kutsuttu")
  148.  
  149. // this is the url where we want to get our data from
  150. val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
  151.  
  152. // Request a string response from the provided URL.
  153. val stringRequest: StringRequest = object : StringRequest(
  154. Request.Method.GET, JSON_URL,
  155. Response.Listener { response ->
  156.  
  157. // print the response as a whole
  158. // we can use GSON to modify this response into something more usable
  159. Log.d("TESTI", response)
  160.  
  161. },
  162. Response.ErrorListener {
  163. // typically this is a connection error
  164. Log.d("TESTI", it.toString())
  165. })
  166. {
  167. @Throws(AuthFailureError::class)
  168. override fun getHeaders(): Map<String, String> {
  169.  
  170. // basic headers for the data
  171. val headers = HashMap<String, String>()
  172. headers["Accept"] = "application/json"
  173. headers["Content-Type"] = "application/json; charset=utf-8"
  174. return headers
  175. }
  176. }
  177.  
  178. // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  179. // if using this in an activity, use "this" instead of "context"
  180. val requestQueue = Volley.newRequestQueue(context)
  181. requestQueue.add(stringRequest)
  182. }
  183.  
  184. override fun onDestroyView() {
  185. super.onDestroyView()
  186. _binding = null
  187. }
  188. }
  189.  
  190. // muutetaan data GSONilla Kotlin-formaattiin Comment.kt -luokan avulla:
  191.  
  192. // apufunktio/metodi, joka hakee dataa rajapinnasta
  193. fun getComments() {
  194. Log.d("TESTI", "getComments() kutsuttu")
  195.  
  196. // this is the url where we want to get our data from
  197. val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
  198.  
  199. // haetaan GSON-objekti käytettäväksi
  200. val gson = GsonBuilder().setPrettyPrinting().create()
  201.  
  202. // Request a string response from the provided URL.
  203. val stringRequest: StringRequest = object : StringRequest(
  204. Request.Method.GET, JSON_URL,
  205. Response.Listener { response ->
  206.  
  207. // print the response as a whole
  208. // we can use GSON to modify this response into something more usable
  209. // Log.d("TESTI", response)
  210.  
  211. // muutetaan x-määrä kommentteja -> Kotlin-olioiksi/muuttujiksi
  212. var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
  213.  
  214. // kokeillaan käyttää rows-listaa, saadaanko dataa ulos
  215. Log.d("TESTI", "Kommenttien määrä: " + rows.size)
  216.  
  217. // kokeillaan loopata läpi kaikki kommentit, tulostetaan jokainen email
  218. for(item : Comment in rows) {
  219. Log.d("TESTI", item.email.toString())
  220. }
  221.  
  222.  
  223. },
  224. Response.ErrorListener {
  225. // typically this is a connection error
  226. Log.d("TESTI", it.toString())
  227. })
  228. {
  229. @Throws(AuthFailureError::class)
  230. override fun getHeaders(): Map<String, String> {
  231.  
  232. // basic headers for the data
  233. val headers = HashMap<String, String>()
  234. headers["Accept"] = "application/json"
  235. headers["Content-Type"] = "application/json; charset=utf-8"
  236. return headers
  237. }
  238. }
  239.  
  240. // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  241. // if using this in an activity, use "this" instead of "context"
  242. val requestQueue = Volley.newRequestQueue(context)
  243. requestQueue.add(stringRequest)
  244. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement