How to read JSON from Url using kotlin Android?
Asked Answered
D

8

13

Am using kotlin for developing the application.Now i want to get JSON data from server.

In java am implemented Asyntask as well as Rxjava for read JSON from Url . Am also search in google but i cant get proper details for my requirement.

How can i read JSON from Url using kotlin?

Decompound answered 3/7, 2017 at 10:43 Comment(1)
If you want in Kotlin just simple answer here https://mcmap.net/q/850449/-how-to-read-json-from-url-using-kotlin-androidRenae
B
17

I guess you're trying to read the response from a server API, which you expect to be a string with JSON. To do so, you can use:

val apiResponse = URL("yourUrl").readText()

From the docs:

Reads the entire content of this URL as a String using UTF-8 or the specified charset.

This method is not recommended on huge files.

Note that, if you're using this inside an Android activity, the app crashes because you're blocking the main thread with an async call. To avoid the app from crashing, I recommend you use Anko. More precisely, you just have to add the commons dependency –not the entire library–.

You can find more info in this blog post

Basrhin answered 23/8, 2017 at 16:49 Comment(5)
@Paul-Sebastian Not only it answers the question, but it is the only one that answers how to do it without using Java libraries. How is it misleading?Basrhin
Sorry, I think last time I tried your answer it didn't work but I don't remember why exactly. Just ignore me. Sorry.Ablepsia
Also sorry for the downvote. Perhaps if you can check your answer that it works and edit it, I can upvote in exchange.Ablepsia
I see that most of here read only the code in your answer, but not answer itself. Just read "more info" before you downvote this brilliant answer!Meditate
Anko library is now deprecated, so please update your comment.Referee
M
5

Update / Note: I've written an entire step by step tutorial on this topic, here. While it's up to you what third party libraries to use (there are some mentioned in the other answers), Retrofit is by far the defacto standard being used these days. Also, it has built in support for coroutines. Your networking code should be asynchronous and your code will be much cleaner, easier to follow and debug, etc. if you use coroutines rather than the old callback methodology. The aforementioned tutorial even shows you how to easily update old code from callbacks to use coroutines, instead.

readText() is the approach Antonio Leiva uses when he introduces Networking in his book Kotlin for Android Developers (and also in the blog post as per dgrcode's answer) However I'm not sure if readText() is the right approach in general for requesting JSON responses from a URL as the response can be very large (Even Antonio mentions affirms the fact that Kotlin docs say there is a size limit to readText). According to this discussion, you should be using streams instead of readText. I would like to see a response to this answer using that approach or whatever is most concise and optimal in Kotlin, without adding library dependencies.

See also this thread

Note also that Antonio does offer alternatives in that blog post for situations when readText() is not the appropriate choice. I'd love to see someone provide some clarity on when it is appropriate or not though.

Manouch answered 17/12, 2017 at 23:57 Comment(1)
It's a great solution. Thank you!!Depravity
D
4

Try this

fun parse(json: String): JSONObject? {
        var jsonObject: JSONObject? = null
        try {
            jsonObject = JSONObject(json)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonObject
    }
Drenthe answered 3/7, 2017 at 11:5 Comment(1)
Existing Android libraries are compatible with Kotlin, you can you retrofit or your choice to fetch data.Drenthe
D
4

Finally am getting answer from Here

Read Json data using Retrofit 2.0 RxJava, RxAndroid, Kotlin Android Extensions.

  fun provideRetrofit(): Retrofit {
    return Retrofit.Builder()
            .baseUrl("https://www.example.com")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()
    }

Module

interface  Api {
@GET("/top.json")
fun getTop(@Query("after") after: String,
           @Query("limit") limit: String): Call<NewsResponse>;
}
Decompound answered 3/7, 2017 at 12:46 Comment(0)
H
1

You can use Volley or Retrofit library in Kotlin.Actually you can use all Java libraries in Kotlin.

Volley is more easier but Retrofit more faster than Volley.Your choice.

Volley Link

Retrofit Link

Hilton answered 3/7, 2017 at 11:33 Comment(0)
O
0

I have a fragment_X (class + layout) where i would like to read the online Json file, (you also able to read txt file), and show the content to TextView.

==> NOTE: give application have a right to access internet in Manifest.

class Fragment_X: Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_X, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if(isNetworkAvailable()) {
            val myRunnable = Conn(mHandler)
            val myThread = Thread(myRunnable)
            myThread.start()
        }
    }


    // create a handle to add message
    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(inputMessage: Message) { if (inputMessage.what == 0) {
            textView.text = inputMessage.obj.toString() }
        } }

    // first, check if network is available.
    private fun isNetworkAvailable(): Boolean { val cm = requireActivity().getSystemService(
        Context.CONNECTIVITY_SERVICE
    ) as ConnectivityManager
        return cm.activeNetworkInfo?.isConnected == true
    }


    //create a worker with a Handler as parameter
    class Conn(mHand: Handler): Runnable {
        val myHandler = mHand
        override fun run() {
            var content = StringBuilder()
            try {
                // declare URL to text file, create a connection to it and put into stream.
                val myUrl = URL("http:.........json")  // or URL to txt file
                val urlConnection = myUrl.openConnection() as HttpURLConnection
                val inputStream = urlConnection.inputStream

                // get text from stream, convert to string and send to main thread.
                val allText = inputStream.bufferedReader().use { it.readText() }
                content.append(allText)
                val str = content.toString()
                val msg = myHandler.obtainMessage()
                msg.what = 0
                msg.obj = str
                myHandler.sendMessage(msg)
            } catch (e: Exception) {
                Log.d("Error", e.toString())
            }
        }

    }

}
Outroar answered 29/9, 2019 at 9:48 Comment(0)
H
0

You can use RequestQueue: https://developer.android.com/training/volley/requestqueue

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

// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://www.google.com"

// 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)
Haveman answered 2/8, 2020 at 18:46 Comment(0)
R
0

In Kotlin it's simple.

If you want to read JSON data from a particular URL.

 val jsonData = getJsonDataFromUrl(URL) // Replace with your JSON URL
 val jsonObject = JSONObject(jsonData)

And simply create the getJsonDataFromUrl function.

fun getJsonDataFromUrl(url: String): String {
    val connection = URL(url).openConnection()
    val reader = BufferedReader(InputStreamReader(connection.getInputStream()))
    val jsonData = StringBuilder()

    var line: String?
    while (reader.readLine().also { line = it } != null) {
        jsonData.append(line)
    }
    reader.close()

    return jsonData.toString()
}
Renae answered 29/5, 2023 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.