0

I am using TheMovieDB API to call the JSON Response of the popular movies and put it into a ScrollView. I have ensured that I have done all the neccessary steps to get the API. However it does not work and does not display anything. If I use another API: "https://jsonplaceholder.typicode.com/posts", it works and the JSON data is displayed into the ScrollView.

Network Utils:

companion object {
        private val TAG: String = NetworkUtils::class.java!!.simpleName

        private val JSON_RESPONSE_URL = "https://api.themoviedb.org/3/movie/popular?api_key=myapikeyishere"

        private val TYPE_SINGLE = 1

        private val TYPE_ALL = 0


        /**
         * Builds the URL used to talk to the weather server using a location. This location is based
         * on the query capabilities of the weather provider that we are using.
         *
         * @param locationQuery The location that will be queried for.
         * @return The URL to use to query the weather server.
         */

        fun buildURLSingleType(id: Int): URL {

            return buildUrl(
                TYPE_SINGLE,
                id
            )
        }

        fun buildURLAll(): URL {

            return buildUrl(
                TYPE_ALL,
                0
            )

        }

        private fun buildUrl(type: Int, id: Int): URL {

            var uri = Uri.parse(JSON_RESPONSE_URL).buildUpon()

            if (type == TYPE_SINGLE) {
                uri.appendPath("1").build()
            }

            val builtUri = uri.build()


            var url: URL? = null
            try {
                url = URL(builtUri.toString())
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            }

            Log.v(TAG, "Built URI " + url!!)

            return url
        }


        /**
         * This method returns the entire result from the HTTP response.
         *
         * @param url The URL to fetch the HTTP response from.
         * @return The contents of the HTTP response.
         * @throws IOException Related to network and stream reading
         */

        @Throws(IOException::class)
        fun getResponseFromHttpUrl(url: URL): String? {
            val urlConnection = url.openConnection() as HttpURLConnection
            try {
                val `in` = urlConnection.getInputStream()

                val scanner = Scanner(`in`)
                scanner.useDelimiter("\\A")


                val hasInput = scanner.hasNext()
                return if (hasInput) {
                    scanner.next()
                } else {
                    null
                }
            } catch (ex: Exception) {

                Log.d(TAG, ex.toString())


            } finally {
                urlConnection.disconnect()
            }

            return null
        }
    }

The Activity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_network)

    }


    override fun onResume() {
        super.onResume()

        val scope = CoroutineScope(Job() + Dispatchers.IO)



        var nwMutipleItemsJob = scope.async(Dispatchers.IO)
        {
            var nwURL = NetworkUtils.buildURLAll()

            val response = NetworkUtils.getResponseFromHttpUrl(nwURL)

            response
        }

        scope.async(Dispatchers.Default)
        {
            var response = nwMutipleItemsJob.await()
            var jsonResponse = JSONArray(response)
            var msg = "$response\n\n"
            for(i in 0 until jsonResponse.length())
            {
                var jsonItem = jsonResponse.getJSONObject(i)
//                var userid = jsonItem.getInt("userId")

//                var id = jsonItem.getInt("adult")
//                var title = jsonItem.getString("title")
//                var body = jsonItem.getString("body")

//                msg += "item $i\n\nid = \n = $id\n"
            }

            withContext(Dispatchers.Main)
            {
                tvJSONMultipleItemDisplay.text = msg
            }
        }
  }
}

layout activity:

 <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tvJSONMultipleItemDisplay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            />

    </ScrollView>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

However it does not work and does not display anything. ? Did you find any error ?.

Please add logs in your getResponseFromHttpUrl and onResume that will help you to find and fix the issue.

How to debug ?.

Ref : https://stackoverflow.com/a/62019186/9909365

On the Android, the log of device display on Tab Logcat, not on console as the Chrome. You can see the log in this tab, and remember build your App in the debug mode.
Edit: If you want to see all the log, you can switch the option Show only Application selected to No filter

For more information, you can find in this link

Android Studio Debug

How to add logs ?

Ref : https://developer.android.com/studio/debug/am-logcat

The Logcat window in Android Studio displays system messages, such as when a garbage collection occurs, and messages that you added to your app with the Log class. It displays messages in real time and keeps a history so you can view older messages.

To display just the information of interest, you can create filters, modify how much information is displayed in messages, set priority levels, display messages produced by app code only, and search the log. By default, logcat shows the log output related to the most recently run app only.

When an app throws an exception, logcat shows a message followed by the associated stack trace containing links to the line of code.

As of Android Studio 2.2, the Run window also displays log messages for the current running app. Note that you can configure the logcat output display, but not the Run window.

Write log messages Ref : https://developer.android.com/studio/debug/am-logcat#WriteLogs

The Log class allows you to create log messages that appear in logcat. Generally, you should use the following log methods, listed in order from the highest to lowest priority (or, least to most verbose):

Log.e(String, String) (error)

Log.w(String, String) (warning)

Log.i(String, String) (information)

Log.d(String, String) (debug)

Log.v(String, String) (verbose)
Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65