Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Edistynyt mobiiliohjelmointi, 20.2.2023
- // kun oma Directus Cloud API on luotu, feedback -collection ja DataReader -käyttäjäryhmä onnistuneesti tehty,
- // voidaan kokeilla rajapinnan toimivuus nettiselaimella. Käytä seuraavanlaista osoitetta, ja korvaa oman rajapintasi
- // tiedot oikeisiin kohtiin
- https://OMAN_DIRECTUSIN_OSOITETUNNUS.directus.app/items/feedback/?access_token=OMA_ACCESS_TOKEN_TÄHÄN
- // kun lähetetään dataa, esimerkki-JSON ilman id:tä:
- {
- "name": "Insomnia test",
- "location": "Internet",
- "value": "Insomnia sanoo terve!"
- }
- // id:tä ei tarvitse antaa itse, koska Directus huolehtii siitä itse kun uutta dataa luodaan
- 1. Luo uusi fragment -> FeedbackReadFragment, ja lisää päävalikkoon. Kopioi pohjaksi binding layeria käyttävä pohja (esim. DataReadFragment)
- 2. json2kt.com -> tee feedback-datasta tarvittava data-luokka, ja kopioi se Android-projektiin (kansioon datatypes -> feedback)
- 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.
- 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)
- // esimerkki-JSON json2kt.comia varten:
- {
- "id": 2,
- "name": "Test Person",
- "location": "Somewhere",
- "value": "This is a test feedback."
- }
- ################################################################
- #### OHJAAJAN LUENTOKOODIT YLLÄOLEVIEN OHJEIDEN MUKAISESTI #####
- ################################################################
- // lisätään myöhemmin
- // uusi fragment -> FeedbackReadFragment, käytä mobile navigation työkalua
- // uuden fragmentin ulkoasu, lisätään ListView:
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout 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"
- tools:context=".FeedbackReadFragment">
- <ListView
- android:id="@+id/listView_feedbacks"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
- </FrameLayout>
- FeedbackReadFragment.kt:
- class FeedbackReadFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentFeedbackReadBinding? = 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 = FragmentFeedbackReadBinding.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
- }
- }
- // lisätään fragmentiin Volley-koodi, muista laittaa Directusin Access token local.properties-tiedostoon
- class FeedbackReadFragment : Fragment() {
- // change this to match your fragment name
- private var _binding: FragmentFeedbackReadBinding? = 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 = FragmentFeedbackReadBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // the binding -object allows you to access views in the layout, textviews etc.
- getFeedbacks()
- return root
- }
- fun getFeedbacks() {
- // this is the url where we want to get our data
- // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
- // localhost refers to the Android device instead of your computer
- val JSON_URL = "https://xxxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
- // Request a string response from the provided URL.
- val stringRequest: StringRequest = object : StringRequest(
- Request.Method.GET, JSON_URL,
- Response.Listener { response ->
- 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> {
- // we have to specify a proper header, otherwise Apigility will block our queries!
- // define we are after JSON 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.
- val requestQueue = Volley.newRequestQueue(context)
- requestQueue.add(stringRequest)
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
- // kokeillaan käyttää GSONia
- // tallennetaan tähän listaan myöhemmin kaikki feedbackit (Volleyn ja GSONin avulla)
- var feedbacks : List<Feedback> = emptyList();
- fun getFeedbacks() {
- // this is the url where we want to get our data
- // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
- // localhost refers to the Android device instead of your computer
- val JSON_URL = "https://xxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
- 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 ->
- val jObject = JSONObject(response)
- val jArray = jObject.getJSONArray("data")
- feedbacks = gson.fromJson(jArray.toString() , Array<Feedback>::class.java).toList()
- for(item in feedbacks) {
- Log.d("ADVTECH", item.name.toString())
- }
- },
- Response.ErrorListener {
- // typically this is a connection error
- Log.d("ADVTECH", it.toString())
- })
- {
- @Throws(AuthFailureError::class)
- override fun getHeaders(): Map<String, String> {
- // we have to specify a proper header, otherwise Apigility will block our queries!
- // define we are after JSON 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.
- val requestQueue = Volley.newRequestQueue(context)
- requestQueue.add(stringRequest)
- }
- /// kytketään ListViewiin feedbacks-data:
- // tallennetaan tähän listaan myöhemmin kaikki feedbackit (Volleyn ja GSONin avulla)
- var feedbacks : List<Feedback> = emptyList();
- fun getFeedbacks() {
- // this is the url where we want to get our data
- // Note: if using a local server, use http://10.0.2.2 for localhost. this is a virtual address for Android emulators, since
- // localhost refers to the Android device instead of your computer
- val JSON_URL = "https://xxxxxxxx.directus.app/items/feedback/?access_token=${BuildConfig.DIRECTUS_ACCESS_TOKEN}"
- 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 ->
- val jObject = JSONObject(response)
- val jArray = jObject.getJSONArray("data")
- feedbacks = gson.fromJson(jArray.toString() , Array<Feedback>::class.java).toList()
- for(item in feedbacks) {
- Log.d("ADVTECH", item.name.toString())
- }
- // käytetään valmista ListView-adapteria
- val adapter = ArrayAdapter(context as Context, android.R.layout.simple_list_item_1, feedbacks)
- binding.listViewFeedbacks.adapter = adapter
- },
- Response.ErrorListener {
- // typically this is a connection error
- Log.d("ADVTECH", it.toString())
- })
- {
- @Throws(AuthFailureError::class)
- override fun getHeaders(): Map<String, String> {
- // we have to specify a proper header, otherwise Apigility will block our queries!
- // define we are after JSON 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.
- val requestQueue = Volley.newRequestQueue(context)
- requestQueue.add(stringRequest)
- }
- // jotta data näyttäisi paremmalta ListViewissä, voimme yliajaa data-luokan toString-metodin (tämä ominaisuus tulee Javasta)
- // voit itse päättää mitä toStringissä tulostetaan, tässä esimerkissä tulee nimi + palauteteksti
- data class Feedback (
- @SerializedName("id" ) var id : Int? = null,
- @SerializedName("name" ) var name : String? = null,
- @SerializedName("location" ) var location : String? = null,
- @SerializedName("value" ) var value : String? = null
- )
- {
- override fun toString(): String {
- val text = name.toString() + ":" + value.toString()
- return text
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement