The following code is intended to extract data from a potentially null JSON response. What is the bug, and how would you fix it?
Android interview question for Advanced practice.
Answer
A NullPointerException might occur if jsonResponse, the "user" object, or the "name" or "age" fields are null.
Explanation
The code directly accesses nested JSON objects and fields without checking for null values at each step. If jsonResponse, the "user" object, or the "name" or "age" fields are null, a NullPointerException will be thrown. To fix this, you need to use safe calls and provide default values using the Elvis operator: kotlin val jsonResponse: JSONObject? = getJsonResponse() val name = jsonResponse?.getJSONObject("user")?.getString("name") ?: "Unknown" val age = jsonResponse?.getJSONObject("user")?.getInt("age") ?: 0 This revised code gracefully handles the potential null values at each level of access.