'Default values from Retrofit Server response are being shown as null

I am calling an api which will gives me some values and some not. So i have given some variables default values. But even when i am not getting them from server , they are being shown as null in log and app is crashing.

Here is the model class:

data class FeedbackData(

    var questionNumber: Int = 0,
    var imageUri: Uri? = null,

    @SerializedName("id") val id: Int,
    @SerializedName("question") val question: String? = null,
    @SerializedName("answer") var answer: Answer = Answer()

)

data class Answer(

    @SerializedName("description") var description: String = "",
    @SerializedName("image") var image: String = ""
)

if you see i have given answer a default object (default initialization) incase server doesnt send it. My requirement is that if server sends it i should have it,if not then i should be able to write that answer object. But i am getting null pointer exception when i am trying to access that answer object.

Here is the log

 E/xoxo: received list: [FeedbackData(questionNumber=0, imageUri=null, id=1, question=How was the event?, answer=null), FeedbackData(questionNumber=0, imageUri=null, id=2, question=Did you face any issue?, answer=null)

And here is the server response:

{"id":1,"question":"How was the event?"},
{"id":2,"question":"Did you face any issue?"}



Solution 1:[1]

So for now i have given value to all the fields above, to id also which did not have default value and now it seems to work. It is seeming like a cheat solution but its working.

Solution 2:[2]

Based on the code you have shown, you are initializing

var answer: Answer = Answer()

But since server is returning null, it is replacing the default Answer with null value. One possible solution could be to provide getter method, something on these lines

var name: answer : Answer
        get() = field?:Answer()

Note: Verify syntax.

Solution 3:[3]

If you are using progaurd, keep your model classes away from obfuscation. Use keepclassmembers in progaurd.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cassius
Solution 2 prashant
Solution 3 Satheesh