Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Edistynyt mobiiliohjelmointi, 27.3.2023
- // haetaan yksittäinen Comment-data rajapinnasta, esim:
- https://jsonplaceholder.typicode.com/comments/1
- Käytetään json2kt.com palvelua ja generoidaan dataluokka:
- package com.example.OMANPROJEKTINPAKETTITÄHÄN
- 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
- )
- // GSON ja Volley, tarvitaan importitit. Gradle Scripts -> build.gradle (Module:app):
- // dependencies -lohkon sisälle jatkoksi:
- implementation 'com.android.volley:volley:1.2.1'
- implementation 'com.google.code.gson:gson:2.10.1'
- // lisätään myös AndroidManifestiin permissionit:
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- Huom: koska Android ei päivitä manifestin permissioneja enää asennuksen jälkeen,
- Volley -koodi ei enää toimi tällä asennuksella koska se ei saa yhteyttä internetiin.
- Tässä vaiheessa emulaattori kiinni -> kolmen pisteen valikko -> Wipe Data (device manager)
- #########################################################################
- TEE UUSI FRAGMENT mobile_navigation -työkalun avulla: CommentDataFragment
- #########################################################################
- Lisätään CommentDataFragment päävalikkkoon (res -> menu -> activity_main_drawer.xml)
- Lisätään myös MainActivityn appBarConfigurationin listaan fragment, esim:
- appBarConfiguration = AppBarConfiguration(
- setOf(
- R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.dataFragment,
- R.id.commentDataFragment
- ), drawerLayout
- )
- // otetaan binding layer käyttöön CommentDataFragmentissa
- class CommentDataFragment : Fragment() {
- private var _binding: FragmentCommentDataBinding? = 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 = FragmentCommentDataBinding.inflate(inflater, container, false)
- val root: View = binding.root
- return root
- }
- override fun onDestroyView() {
- super.onDestroyView()
- _binding = null
- }
- }
- // muutetaan ulkoasuksi LinearLayout ja lisätään nappi jolla haetaan dataa
- <?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=".CommentDataFragment">
- <Button
- android:id="@+id/button_get_comments"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="GET DATA" />
- </LinearLayout>
- // tehdään apufunktio/metodi, johon voidaan keskittää Volley-koodi, eli raakadatan lataaminen
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- _binding = FragmentCommentDataBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // haetaan dataa kun nappia painetaan
- binding.buttonGetComments.setOnClickListener {
- getComments()
- }
- return root
- }
- // apufunktio/metodi, joka hakee dataa rajapinnasta
- fun getComments() {
- Log.d("TESTI", "getComments() kutsuttu")
- }
- // haetaan Volleylla dataa, muista tyhjentää emulaattori, jotta permissionit päivittyy, muuten tulee NoConnectionError
- class CommentDataFragment : Fragment() {
- private var _binding: FragmentCommentDataBinding? = 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 = FragmentCommentDataBinding.inflate(inflater, container, false)
- val root: View = binding.root
- // haetaan dataa kun nappia painetaan
- binding.buttonGetComments.setOnClickListener {
- getComments()
- }
- return root
- }
- // apufunktio/metodi, joka hakee dataa rajapinnasta
- fun getComments() {
- Log.d("TESTI", "getComments() kutsuttu")
- // 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("TESTI", response)
- },
- Response.ErrorListener {
- // typically this is a connection error
- Log.d("TESTI", 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
- }
- }
- // muutetaan data GSONilla Kotlin-formaattiin Comment.kt -luokan avulla:
- // apufunktio/metodi, joka hakee dataa rajapinnasta
- fun getComments() {
- Log.d("TESTI", "getComments() kutsuttu")
- // this is the url where we want to get our data from
- val JSON_URL = "https://jsonplaceholder.typicode.com/comments"
- // haetaan GSON-objekti käytettäväksi
- 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("TESTI", response)
- // muutetaan x-määrä kommentteja -> Kotlin-olioiksi/muuttujiksi
- var rows : List<Comment> = gson.fromJson(response, Array<Comment>::class.java).toList()
- // kokeillaan käyttää rows-listaa, saadaanko dataa ulos
- Log.d("TESTI", "Kommenttien määrä: " + rows.size)
- // kokeillaan loopata läpi kaikki kommentit, tulostetaan jokainen email
- for(item : Comment in rows) {
- Log.d("TESTI", item.email.toString())
- }
- },
- Response.ErrorListener {
- // typically this is a connection error
- Log.d("TESTI", 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)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement