Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: Cannot find getter for field in Android Room

Tags:

java

android

This is a simple a class in android studio:

package com.loghty.bahaa.loghty;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;


@Entity (tableName = "Chars")
public class Chars {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "char_Id")
    private int pCId;

    @NonNull
    @ColumnInfo(name = "char_field")
    private String mcharField;

    // Getters and setters

    public String getMcharField() {
        return mcharField;
    }

    public void setMcharField(@NonNull String mcharField) {
        this.mcharField = mcharField;
    }

    public int getpCId() {
        return pCId;
    }
}

But when I build the app I get this error in the pCId field:

error: Cannot find getter for field

I checked the code many times but nothing is strange. where is the error exactly ?

like image 213
Bahaa Salaheldin Avatar asked Jul 14 '18 23:07

Bahaa Salaheldin


3 Answers

Change the variable from private to protected or public

from private int pCId;

to protected int pCId;

like image 54
Boadu Philip Asare Avatar answered Nov 12 '22 22:11

Boadu Philip Asare


This work for me:

  1. add the constructor with and without the auto generated id
  2. add the @Ignore annotation to the constructor without the auto generated id
  3. add the getter with camelCase
  4. clean all the data before the first install on device because i don't want to do the migration.

    @Entity(tableName = "words")
    public class Word {
    
    @PrimaryKey(autoGenerate = true)
    private int id;
    
    @NonNull
    @ColumnInfo(name = "word")
    private String mWord;
    
    public Word(int id, @NonNull String mWord) {
        this.id = id;
        this.mWord = mWord;
    }
    
    @Ignore
    public Word(@NonNull String mWord) {
        this.mWord = mWord;
    }
    
    public int getId() { return id; }
    
    public String getWord(){ return this.mWord; }
    }
    
like image 2
madwyatt Avatar answered Nov 12 '22 23:11

madwyatt


I had the same issue when the getter fun return type was different from the field's type (DateTime vs String):

val timestamp: String = DateTime.now().toString()

fun getTimestamp(): DateTime = DateTime.parse(timestamp)

Room was skipping a generation of getTimestamp() fun for the timestamp field because Room was thinking it's already created. Wheres, the type mismatch caused an exception because types are not matching.

The solution was to rename the getter fun:

val timestamp: String = DateTime.now().toString()

fun getTime(): DateTime = DateTime.parse(timestamp)
like image 1
Val Avatar answered Nov 12 '22 23:11

Val