API data in kotlin fragment

独自空忆成欢 提交于 2021-01-28 06:01:46

问题


I am trying to use Drawer activity, seems that it has 3 files to just show simple text as This is home Fragment :|

Anyway, I have tracked back all those files and found fragment_home.xml, HomeFragment.kt and HomeViewModel.kt

Question

How should I call for API data trough fragments?

Code

my code

Based on android studio documentation this is the code that I should use in order to get my api data.

val textView = findViewById<TextView>(R.id.TextView)

// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://example.com/api/listings"

// Request a string response from the provided URL.
val stringRequest = StringRequest(
    Request.Method.GET, url,
    Response.Listener<String> { response ->
        // Display the first 500 characters of the response string.
        textView.text = "Response is: ${response.substring(0, 500)}"
    },
    Response.ErrorListener { textView.text = "That didn't work!" })

// Add the request to the RequestQueue.
queue.add(stringRequest)

PS: I have tried this code above in empty activity it's working

HomeViewModel.kt

class HomeViewModel : ViewModel() {

    private val _text = MutableLiveData<String>().apply {
        value = "This is home Fragment"
    }
    val text: LiveData<String> = _text
}

HomeFragment.kt

class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = root.findViewById(R.id.text_home)
        homeViewModel.text.observe(this, Observer {
            textView.text = it
        })
        return root
    }
}

fragment_home.xml

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Please note, before you try to give down-vote: I am aware this question probably is very basic question, but note that it's my first time ever using fragments (basically newbie in android studio), so yes my questions are kind of basic :)


回答1:


for calling the API from fragment, you can do

class HomeFragment : Fragment() {

  private lateinit var homeViewModel: HomeViewModel

            override fun onCreateView(
                inflater: LayoutInflater,
                container: ViewGroup?,
                savedInstanceState: Bundle?
            ): View? {
                homeViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)

                val root = inflater.inflate(R.layout.fragment_home, container, false)

                val textView: TextView = root.findViewById(R.id.text_home)

                //calling the API
                callAPIDemo(textView)

               // homeViewModel.text.observe(this, Observer {
               //     textView.text = it
               // })

                return root
            }

     fun callAPIDemo(textView: TextView) {
        // Instantiate the RequestQueue.
        val queue = Volley.newRequestQueue(activity)
        val url = "https://example.com/api/listings"

        // Request a string response from the provided URL.
        val stringRequest = StringRequest(
                Request.Method.GET, url,
                Response.Listener<String> { response ->
                    // Display the first 500 characters of the response string.
                    textView.text = "Response is: ${response.substring(0, 500)}"
                },
                Response.ErrorListener { textView.text = "That didn't work!" })

        // Add the request to the RequestQueue.
        queue.add(stringRequest)
    }

        }


来源:https://stackoverflow.com/questions/60096397/api-data-in-kotlin-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!