Nguyễn Huy
Nguyễn Huy

Reputation: 3

Query data from room but response not enough fields of model?

I have a response object:

class TopicResponse(
    var id: Int = 0,
    val name: String,
    var wordNumber: Int,
    @Ignore
    var imageUrl:String
)

My query:

@Dao
interface TopicDao {
    @Query("select Topic.id,Topic.name,count(*) as wordNumber 
    from Topic,WordDetails 
    where Topic.id = WordDetails.topicId group by Topic.id")
    fun getTotalTopic(): List<TopicResponse>
}

Response have 3 fields: id, name, wordNumber. I can't build app with error:

Tried the following constructors but they failed to match:
TopicResponse(int,java.lang.String,int,java.lang.String) -> 
[param:id -> matched field:id, param:name -> matched field:name, param:wordNumber -> matched field:wordNumber, param:imageUrl -> matched field:unmatched]D:\personal\flashcardgame\FlashCard\app\build\tmp\kapt3\stubs\debug\com\ribisoft\english\flashcard\model\TopicResponse.java:9: error: Cannot find setter for field.
private final java.lang.String name = null;

Please help me, thank you very much!

Upvotes: 0

Views: 45

Answers (2)

Gavin Wright
Gavin Wright

Reputation: 3212

Where does the imageUrl come from if not from the API? I'll just assume you're getting it from somewhere else. In that case, you should use a NetworkTopicResponse which looks like this:

class NetworkTopicResponse(
var id: Int = 0,
val name: String,
var wordNumber: Int
)

And then you can transform that into a TopicResponse later on.

Upvotes: 0

Jenea Vranceanu
Jenea Vranceanu

Reputation: 4694

You cannot use @Ignore annotation on a constructor argument.

Here are the targets of @Ignore annotation:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR})

It means you can ignore method, a field of a class or a whole constructor. In your particular case, the primary constructor requires three arguments name, wordNumber and imageUrl at least because they do not have default values.

The following configuration should work:

class TopicResponse {
    var id: Int = 0
    val name: String
    var wordNumber: Int
    var imageUrl:String

    @Ignore
    constructor(
        id: Int = 0,
        name: String,
        wordNumber: Int,
        imageUrl:String
    ) {
        this.id = id
        this.name = name
        this.wordNumber = wordNumber
        this.imageUrl = imageUrl
    }
    
    // This constructor will be used by DAO
    constructor(id: Int = 0, name: String, wordNumber: Int): this(id, name, wordNumber, "")
}

Upvotes: 1

Related Questions