android – How can I try catch a val in fetch data successfully?-ThrowExceptions

Exception or error:

I am trying to fetch a JSONObject “image” that is sometimes a null value, so I set a try {} catch {} for my val jsonMedia in order to make it nullable but Im not sure if I’m missing something because it doesnt seem to work.

Whenever I comment out the jsonMedia my fetch works fine so I’ll focus on just sharing the fetch of the “image” so the data I share doesnt get confusing.

1st. Ill show how the “image” is in the database and what I mean by “sometimes” has a null value
– null:

{
    "listCar": [
   {
    //other data
    "image": null,
    //other data
   }
 ]
}
  • when it contains an image:
{
    "listCar": [
   {
    //other data
     "image": {
                "path": "Upload/UploadCarMain/UploadCarMain-200-200/30032235992008220498istanbul_adalarCar195.jpg",
                "name": "30032235992008220498istanbul_adalarCar195.jpg"
            },
    //other data
   }
 ]
}

Now my fetch data was followed by a course I’m watching the only difference is the values of “image” in the database Im using arent like the course which did not contain null values in their image path

Now here is my “Car” class that is supposed to get the image:

class Car(other data, val image: String?, other data) {
    override fun toString(): String {
        return "Car(//other data, image='$image', //other data')"
    }
}

and here is my fetch code where I am trying to try {} catch(){} my “jsonMedia” image JSONOBject:

override fun doInBackground(vararg params: String?): ArrayList<Car> {
        Log.d(TAG, "doInBackground starts")

        val carList = ArrayList<Car>()
        try {
            val jsonData = JSONObject(params[0])
            val itemsArray = jsonData.getJSONArray("listCar")

            for (i in 0 until itemsArray.length()) {
                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: IllegalArgumentException) {null}
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)
                Log.d(TAG, ".doInBackground $carObject")
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            Log.e(TAG, "doInBackground: Error processing json data. ${e.message}")
            cancel(true)
            listener.onError(e)
        }

        Log.d(TAG, ".doInBackground ends")
        return carList
    }

    override fun onPostExecute(result: ArrayList<Car>) {
        Log.d(TAG, "onPostExecute starts")
        super.onPostExecute(result)
        listener.onDataAvailable(result)
        Log.d(TAG, ".onPostExecute ends")
    }
}

and here is the error I get when i run the code:

2020-02-14 16:42:16.483 26642-26684/com.example.wasit E/GetFlickrJsonData: doInBackground: Error processing json data. Value null at image of type org.json.JSONObject$1 cannot be converted to JSONObject
How to solve:

Just modify the code like this. Exception class is the Parent class of all exception and provide exact cause of error.

for (i in 0 until itemsArray.length()) {

try {

                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = jsonCar.getJSONObject("image")
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)

} catch (ex: Exception) {
 Log.d(TAG, ex.localizedMessage.toString())
}

            }

###

I found a way.

I had to wrap my “jsonMedia” in the following try catch:

val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: JSONException) {
                    null
                }

Now my images that are null contain placeholders and the others work fine!

Leave a Reply

Your email address will not be published. Required fields are marked *