Advertisement
tuomasvaltanen

Untitled

Feb 20th, 2023 (edited)
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.67 KB | None | 0 0
  1. // Edistynyt mobiiliohjelmointi, 20.2.2023
  2.  
  3. // kun oma Directus Cloud API on luotu, feedback -collection ja DataReader -käyttäjäryhmä onnistuneesti tehty,
  4. // voidaan kokeilla rajapinnan toimivuus nettiselaimella. Käytä seuraavanlaista osoitetta, ja korvaa oman rajapintasi
  5. // tiedot oikeisiin kohtiin
  6.  
  7. https://OMAN_DIRECTUSIN_OSOITETUNNUS.directus.app/items/feedback/?access_token=OMA_ACCESS_TOKEN_TÄHÄN
  8.  
  9. // kun lähetetään dataa, esimerkki-JSON ilman id:tä:
  10. {
  11. "name": "Insomnia test",
  12. "location": "Internet",
  13. "value": "Insomnia sanoo terve!"
  14. }
  15.  
  16. // id:tä ei tarvitse antaa itse, koska Directus huolehtii siitä itse kun uutta dataa luodaan
  17.  
  18. 1. Luo uusi fragment -> FeedbackReadFragment, ja lisää päävalikkoon. Kopioi pohjaksi binding layeria käyttävä pohja (esim. DataReadFragment)
  19.  
  20. 2. json2kt.com -> tee feedback-datasta tarvittava data-luokka, ja kopioi se Android-projektiin (kansioon datatypes -> feedback)
  21.  
  22. 3. FeedbackReadFragment -> käytä Volley-pohjaa, ja lataa kaikki Feedbackit Directusista (esimerkki, Moodlessa), ja tulosta Logiin kaikki feedbackien nimet. Aseta access token local.propertiesiin esim. muuttujaan DIRECTUS_ACCESS_TOKEN.
  23.  
  24. 4. Muuta raaka-JSON Feedback-olioiksi GSONilla (ks. esimerkki Moodlessa miten data-wrapperin saa kierrettyä koodissa, jotta pääsemme feedback-dataan käsiksi). Kytketään lista lopuksi ListViewiin. (ks. esimerkki Moodlessa, oman APIn käyttäminen Androidissa)
  25.  
  26. // esimerkki-JSON json2kt.comia varten:
  27.  
  28. {
  29. "id": 2,
  30. "name": "Test Person",
  31. "location": "Somewhere",
  32. "value": "This is a test feedback."
  33. }
  34.  
  35. ################################################################
  36. #### OHJAAJAN LUENTOKOODIT YLLÄOLEVIEN OHJEIDEN MUKAISESTI #####
  37. ################################################################
  38.  
  39. // lisätään myöhemmin
  40.  
  41. // uusi fragment -> FeedbackReadFragment, käytä mobile navigation työkalua
  42.  
  43. // uuden fragmentin ulkoasu, lisätään ListView:
  44.  
  45. <?xml version="1.0" encoding="utf-8"?>
  46. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  47. xmlns:tools="http://schemas.android.com/tools"
  48. android:layout_width="match_parent"
  49. android:layout_height="match_parent"
  50. tools:context=".FeedbackReadFragment">
  51.  
  52. <ListView
  53. android:id="@+id/listView_feedbacks"
  54. android:layout_width="match_parent"
  55. android:layout_height="match_parent" />
  56. </FrameLayout>
  57.  
  58. FeedbackReadFragment.kt:
  59.  
  60. class FeedbackReadFragment : Fragment() {
  61. // change this to match your fragment name
  62. private var _binding: FragmentFeedbackReadBinding? = null
  63.  
  64. // This property is only valid between onCreateView and
  65. // onDestroyView.
  66. private val binding get() = _binding!!
  67.  
  68. override fun onCreateView(
  69. inflater: LayoutInflater,
  70. container: ViewGroup?,
  71. savedInstanceState: Bundle?
  72. ): View? {
  73. _binding = FragmentFeedbackReadBinding.inflate(inflater, container, false)
  74. val root: View = binding.root
  75.  
  76. // the binding -object allows you to access views in the layout, textviews etc.
  77.  
  78. return root
  79. }
  80.  
  81. override fun onDestroyView() {
  82. super.onDestroyView()
  83. _binding = null
  84. }
  85. }
  86.  
  87.  
  88. // lisätään fragmentiin Volley-koodi, muista laittaa Directusin Access token local.properties-tiedostoon
  89.  
  90. class FeedbackReadFragment : Fragment() {
  91. // change this to match your fragment name
  92. private var _binding: FragmentFeedbackReadBinding? = null
  93.  
  94. // This property is only valid between onCreateView and
  95. // onDestroyView.
  96. private val binding get() = _binding!!
  97.  
  98. override fun onCreateView(
  99. inflater: LayoutInflater,
  100. container: ViewGroup?,
  101. savedInstanceState: Bundle?
  102. ): View? {
  103. _binding = FragmentFeedbackReadBinding.inflate(inflater, container, false)
  104. val root: View = binding.root
  105.  
  106. // the binding -object allows you to access views in the layout, textviews etc.
  107.  
  108. getFeedbacks()
  109.  
  110. return root
  111. }
  112.  
  113. fun getFeedbacks() {
  114. // this is the url where we want to get our data
  115. // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
  116. // localhost refers to the Android device instead of your computer
  117. val JSON_URL = "https://xxxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
  118.  
  119. // Request a string response from the provided URL.
  120. val stringRequest: StringRequest = object : StringRequest(
  121. Request.Method.GET, JSON_URL,
  122. Response.Listener { response ->
  123.  
  124. Log.d("ADVTECH", response)
  125. },
  126. Response.ErrorListener {
  127. // typically this is a connection error
  128. Log.d("ADVTECH", it.toString())
  129. })
  130. {
  131. @Throws(AuthFailureError::class)
  132. override fun getHeaders(): Map<String, String> {
  133. // we have to specify a proper header, otherwise Apigility will block our queries!
  134. // define we are after JSON data!
  135. val headers = HashMap<String, String>()
  136. headers["Accept"] = "application/json"
  137. headers["Content-Type"] = "application/json; charset=utf-8"
  138. return headers
  139. }
  140. }
  141.  
  142. // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  143. val requestQueue = Volley.newRequestQueue(context)
  144. requestQueue.add(stringRequest)
  145. }
  146.  
  147. override fun onDestroyView() {
  148. super.onDestroyView()
  149. _binding = null
  150. }
  151. }
  152.  
  153. // kokeillaan käyttää GSONia
  154.  
  155. // tallennetaan tähän listaan myöhemmin kaikki feedbackit (Volleyn ja GSONin avulla)
  156. var feedbacks : List<Feedback> = emptyList();
  157.  
  158. fun getFeedbacks() {
  159. // this is the url where we want to get our data
  160. // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
  161. // localhost refers to the Android device instead of your computer
  162. val JSON_URL = "https://xxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
  163.  
  164. val gson = GsonBuilder().setPrettyPrinting().create()
  165.  
  166. // Request a string response from the provided URL.
  167. val stringRequest: StringRequest = object : StringRequest(
  168. Request.Method.GET, JSON_URL,
  169. Response.Listener { response ->
  170. val jObject = JSONObject(response)
  171. val jArray = jObject.getJSONArray("data")
  172.  
  173. feedbacks = gson.fromJson(jArray.toString() , Array<Feedback>::class.java).toList()
  174.  
  175. for(item in feedbacks) {
  176. Log.d("ADVTECH", item.name.toString())
  177. }
  178. },
  179. Response.ErrorListener {
  180. // typically this is a connection error
  181. Log.d("ADVTECH", it.toString())
  182. })
  183. {
  184. @Throws(AuthFailureError::class)
  185. override fun getHeaders(): Map<String, String> {
  186. // we have to specify a proper header, otherwise Apigility will block our queries!
  187. // define we are after JSON data!
  188. val headers = HashMap<String, String>()
  189. headers["Accept"] = "application/json"
  190. headers["Content-Type"] = "application/json; charset=utf-8"
  191. return headers
  192. }
  193. }
  194.  
  195. // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  196. val requestQueue = Volley.newRequestQueue(context)
  197. requestQueue.add(stringRequest)
  198. }
  199.  
  200. /// kytketään ListViewiin feedbacks-data:
  201.  
  202. // tallennetaan tähän listaan myöhemmin kaikki feedbackit (Volleyn ja GSONin avulla)
  203. var feedbacks : List<Feedback> = emptyList();
  204.  
  205. fun getFeedbacks() {
  206. // this is the url where we want to get our data
  207. // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
  208. // localhost refers to the Android device instead of your computer
  209. val JSON_URL = "https://xxxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
  210.  
  211. val gson = GsonBuilder().setPrettyPrinting().create()
  212.  
  213. // Request a string response from the provided URL.
  214. val stringRequest: StringRequest = object : StringRequest(
  215. Request.Method.GET, JSON_URL,
  216. Response.Listener { response ->
  217. val jObject = JSONObject(response)
  218. val jArray = jObject.getJSONArray("data")
  219.  
  220. feedbacks = gson.fromJson(jArray.toString() , Array<Feedback>::class.java).toList()
  221.  
  222. for(item in feedbacks) {
  223. Log.d("ADVTECH", item.name.toString())
  224. }
  225.  
  226. // käytetään valmista ListView-adapteria
  227. val adapter = ArrayAdapter(context as Context, android.R.layout.simple_list_item_1, feedbacks)
  228. binding.listViewFeedbacks.adapter = adapter
  229. },
  230. Response.ErrorListener {
  231. // typically this is a connection error
  232. Log.d("ADVTECH", it.toString())
  233. })
  234. {
  235. @Throws(AuthFailureError::class)
  236. override fun getHeaders(): Map<String, String> {
  237. // we have to specify a proper header, otherwise Apigility will block our queries!
  238. // define we are after JSON data!
  239. val headers = HashMap<String, String>()
  240. headers["Accept"] = "application/json"
  241. headers["Content-Type"] = "application/json; charset=utf-8"
  242. return headers
  243. }
  244. }
  245.  
  246. // Add the request to the RequestQueue. This has to be done in both getting and sending new data.
  247. val requestQueue = Volley.newRequestQueue(context)
  248. requestQueue.add(stringRequest)
  249. }
  250.  
  251.  
  252.  
  253. // jotta data näyttäisi paremmalta ListViewissä, voimme yliajaa data-luokan toString-metodin (tämä ominaisuus tulee Javasta)
  254. // voit itse päättää mitä toStringissä tulostetaan, tässä esimerkissä tulee nimi + palauteteksti
  255. data class Feedback (
  256.  
  257. @SerializedName("id" ) var id : Int? = null,
  258. @SerializedName("name" ) var name : String? = null,
  259. @SerializedName("location" ) var location : String? = null,
  260. @SerializedName("value" ) var value : String? = null
  261.  
  262. )
  263. {
  264. override fun toString(): String {
  265. val text = name.toString() + ":" + value.toString()
  266. return text
  267. }
  268. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement