Android Room library error: Cannot find getter for field - java

I get this error but I couldn't find any solution. I tried many things but still I'm getting this code.
My code is:
https://justpaste.it/4di3y
The error:
error: Cannot find getter for field.
( private Long fie_id )
How I can fix it?

Instead of
public Long getId() {
return fie_id;
}
public void setId(Long id) {
this.fie_id = id;
}
Do
public Long getFie_id() {
return fie_id;
}
public void setFie_id(Long fie_id) {
this.fie_id = fie_id;
}

Maybe you don't believe me but i have to say. I am using Mac and that problem was about the Computer Language. I was using Turkish Language and i have changed to English and that problem was gone after Invalidate Cache and Restart.
As summary:
Set MacOSX language as English (SystemPreferences -> Language & Region)
Open Android Studio and Perform Invalidate Caches And Restart (File -> Invalidate Caches/Restart -> Invalidate and Restart)

Change all the access modifier to "public". This will solve the issue.
Instead of:
#PrimaryKey
private Long fie_id;
#ColumnInfo(name = "name")
private String name;
Use:
#PrimaryKey
public Long fie_id;
#ColumnInfo(name = "name")
public String name;

Kotlin room does not allow defining variables in entity class start of 'i' character. I had the same error. I solved it, albeit difficult.
Replace id with pId and it will be fine.
For example;
val isrc: String? = "",
instead of
val albumIsrc: String? = "",
If you change the variable in this way, the error will be resolved.
Happy codding.
Note : if system language of your computers is Turkish, this case does.

It has to do with the naming of your PrimaryKey. The signature of your getter and setter should correspond to the name of the variable. Otherwise, Room can't find it.
Which means that the variable id should have getId(), and variable fie_id should have getFie_id() as a getter, the same goes for the setters. So, either rename your PrimaryKey or name your getters and setters accordingly.

For me it was because of an uncapitalized "m". The below works:
#ColumnInfo(name = "foo")
private String mFoo;
public String getMFoo() {
return mFoo;
}
public void setMFoo(String foo) {
this.mFoo = foo;
}
This doesn't:
#ColumnInfo(name = "foo")
private String mFoo;
public String getmFoo() {
return mFoo;
}
public void setmFoo(String foo) {
this.mFoo = foo;
}
Also don't forget to specify the new column in your migration. Something like:
val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE myDataObj "
+ " ADD COLUMN foo TEXT")
}
}

Try to match the name of the setter function as the variable name declared.
Forex.
There is a boolean variable declared like
private boolean attachment_status;
It's getter should be like this
public boolean getattachment_status(){
return attachment_status
}
or u can do like this
public boolean getAttachment_status(){
return attachment_status
}
I declared my getter like this and I was getting the same error
public boolean getAttachment(){
return attachment_status
}
but I refactor it and the problem was solved.

During your programs lifecycle if the encapsulation is incorrect then confusion happens. After viewing your code it seems might be attempting to access something from an eternal class. PrimaryKey id is being called instead of the passed value setId( id ).

Make the variable public:
Private --> Public

It is better to stick with documantation. The structures are sensitive. link of documantation
Sample :
#Entity(tableName = "notes")
public class Note {
#PrimaryKey(autoGenerate = true)
public int id;
#NotNull
#ColumnInfo(name = "note")
public String mNote;
public Note(#NotNull String mNote) {
this.mNote = mNote;
}
public int getId() {
return id;
}
#NotNull
public String getNote() {
return this.mNote;
}}
Had same problem Clear and Rebuild the project options are the answer somehow after the change.

for getter in setter, just follow the Pattern get/set[A-Z]last lenght-1 of the field just like in the example ( field: mWord)
#Entity(tableName = "words")
public class Word {
#PrimaryKey
#NonNull
#ColumnInfo(name = "word")
private String mWord;
public Word(#NonNull String mWord) {
this.mWord = mWord;
}
public String getMWord() {
return mWord;
}
}

Only need to change is fied scope update as "public" instead of "private".
https://github.com/rzwitserloot/lombok/issues/1403

Changing the variable from private to protected worked for me.

If everything is correct, then I have observe this issue mostly in a case of variable kind of pId, uId etc.
change variable name from
private Long pId;
to
private Long pid;
And generate getter and setter using IDE.

Related

Java nested POJO update based on dot annotation

I have a nested POJO structure defined something like this,
public class Employee {
private String id;
private Personal personal;
private Official official;
}
public class Personal {
private String fName;
private String lName;
private String address;
}
public class Official {
private boolean active;
private Salary salary;
}
public class Salary {
private double hourly;
private double monthly;
private double yearly;
}
I get updates from a service with dot annotaion on what value changed, for ex,
id change --> id=100
address change --> personal.address=123 Main Street
hourly salary change --> official.salary.hourly=100
This POJO structure could be 3-4 level deeps. I need to look for this incoming change value and update the corresponding value in POJO. What's the best way of doing it?
If you would like to create Java objects that allows you to edit fields. You can specify your object fields with the public/default/protected access modifiers. This will enable you to get and set fields such as personal.address or official.salary.hours
This approach is typically frowned upon as the object is no longer encapsulated and any calling methods are welcome to manipulate the object. If these fields are not encapsulated with getters and setters, your object is no longer a POJO.
public provides access from any anywhere.
default provides access from any package
protected provides access from package or subclass.
public class Employee {
public String id;
public Personal personal;
public Official official;
}
public class Personal {
public String fName;
public String lName;
public String address;
}
Here's a quick approach using reflection to set fields dynamically. It surely isn't and can't be clean. If I were you, I would use a scripting engine for that (assuming it's safe to do so).
private static void setValueAt(Object target, String path, String value)
throws Exception {
String[] fields = path.split("\\.");
if (fields.length > 1) {
setValueAt(readField(target, fields[0]),
path.substring(path.indexOf('.') + 1), value);
return;
}
Field f = target.getClass()
.getDeclaredField(path);
f.setAccessible(true);
f.set(target, parse(value, f.getType())); // cast or convert value first
}
//Example code for converting strings to primitives
private static Object parse(String value, Class<?> type) {
if (String.class.equals(type)) {
return value;
} else if (double.class.equals(type) || Double.class.equals(type)) {
return Long.parseLong(value);
} else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
return Boolean.valueOf(value);
}
return value;// ?
}
private static Object readField(Object from, String field) throws Exception {
Field f = from.getClass()
.getDeclaredField(field);
f.setAccessible(true);
return f.get(from);
}
Just be aware that there's a lot to improve in this code (exception handling, null checks, etc.), although it seems to achieve what you're looking for (split your input on = to call setValueAt()):
Employee e = new Employee();
e.setOfficial(new Official());
e.setPersonal(new Personal());
e.getOfficial().setSalary(new Salary());
ObjectMapper mapper = new ObjectMapper();
setValueAt(e, "id", "123");
// {"id":"123","personal":{},"official":{"active":false,"salary":{"hourly":0.0,"monthly":0.0,"yearly":0.0}}}
setValueAt(e, "personal.address", "123 Main Street");
// {"id":"123","personal":{"address":"123 Main Street"},"official":{"active":false,"salary":{"hourly":0.0,"monthly":0.0,"yearly":0.0}}}
setValueAt(e, "official.salary.hourly", "100");
// {"id":"123","personal":{"address":"123 Main Street"},"official":{"active":false,"salary":{"hourly":100.0,"monthly":0.0,"yearly":0.0}}}

Proper Constructors to Run all Methods in Java

I have this class and need to know which constructor is needed to create an object that may immediately use all its methods without error
public class Robot {
private boolean fuelEmpty = true;
private int roboID;
private String greeting;
private String securityProtocol;
//insert robot constructor here
public void destroyAllHumans(){
while (fuelEmpty == false) {
//robot begins to destroy all humans
}
}
public int getRoboID(){
return roboID;
}
public void greet(){
System.out.println(greeting);
}
public void setSecurityProtocol(String proto){
securityProtocol = proto;
}
}
For example should look like this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
}
or this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
fuelEmpty = false;
}
or:
public Robot(boolean full, int id, String greet, String proto) {
roboID = id;
greeting = greet;
fuelEmpty = full;
securityProtocol = proto;
}
Which of these (or something else different) is needed so that all the other methods can run without an error?
You can overload the constructor as much as you need, the important thing is
the object gets properly instantiated after you create a new one...
a way can be:
public Robot() {
this(false, 0, "", "");
}
public Robot(int id) {
this(false, id, "", "");
}
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol) {
this.fuelEmpty = fuelEmpty;
this.roboID = roboID;
this.greeting = greeting;
this.securityProtocol = securityProtocol;
}
so look how all other constructors will at the end call internally the
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol)
that will give you the waranty that no matter which constructor is invoked, the Robot is fully created and can invoke all those methods without crashing
The solution works like this:
you look at each of your methods
you check which fields each method is using
you check more closely, if the method breaks when that field has its default value (like null for Objects, or false for booleans)
When you do that for all methods, you get a list of those fields that you need to initialize somehow. Then you could go forward and define a corresponding constructor.
But of course, that is the wrong approach.
The real answer goes like this: you don't put fields into a class because you can. You add them because they are required so that this class can implement the requirements (responsibilities) that you want it to implement. Meaning: you focus on the methods that your class should provide. Then you clarify which fields you need in order to implement these methods.
In other words: you have exactly those fields in your class that your class needs. If you have fields in there that go unused - then you get rid of them.

How to make Morphia set the value of a field as the value returned by a function call?

I'm implementing the "auto-increment" id using strategy described here:
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Basically the value of the seqId field is set by calling an utility function that updates the counter on an auxiliary collection and returns the incremented value. Sounds great.
My issue is in mapping this to be used with Morphia. The tutorial suggests performing the insert (such as in the shell) like so:
db.users.insert(
{
seqId: getNextSequence("userid"),
name: "Sarah C."
}
I'm basically looking to do something like setting the POJO seqId field to something that Morphia will translate into an insert like the one above when I invoke save().
My POJO looks like this:
#Entity
public class User {
#Id
private Long id;
// THIS IS THE FIELD I WANT TO AUTO-INCREMENT
private Long seqId;
private String name;
...
}
The question is: How to make Morphia set the value of a field as the value returned by a function call?
I looked into using the #PrePresist annotation to perform this function call and getting the value, then setting it in the +_id field. That has several drawbacks such as making multiple calls to MongoDB instead of just one, and also the fact that my model objects don't have a reference to the datastore and I'd rather not mix up the concerns.
Is this possible? Any suggestions?
I'm on MongoDB 2.6.6 using the latest Java drivers.
Thanks!
PS: I'm aware that auto-increment is not recommended in large environments. I need it anyways for this specific scenario.
I'll describe the solution that's working for us quite well. Note that this supports auto increments on the class level and a subset of it — so you can count users or admin-users (user with an admin enum or whatever).
This contains the current value for each auto increment field, it's basically a reference:
#Entity(noClassnameStored = true)
public class AutoIncrementEntity {
#Id
protected String key;
protected Long value = 1L;
protected AutoIncrementEntity() {
super();
}
/**
* Set the key name — class or class with some other attribute(s).
*/
public AutoIncrementEntity(final String key) {
this.key = key;
}
/**
* Set the key name and initialize the value so it won't start at 1.
*/
public AutoIncrementEntity(final String key, final Long startValue) {
this(key);
value = startValue;
}
public Long getValue() {
return value;
}
}
In your persistence service, you could use the following to set / create the auto increment automatically:
public <E extends BaseEntity> ObjectId persist(E entity) {
// If it's a user and doesn't yet have an ID, set one; start counting from 1000.
if ((entity instanceof UserEntity) && (((UserEntity) entity).getUserId() == null)) {
((UserEntity) entity).setUserId(
generateAutoIncrement(entity.getClass().getName(), 1000L));
}
// Additionally, set an ID within each user group; start counting from 1.
if ((entity instanceof UserEntity) && (((UserEntity) entity).getRoleId() == null)) {
((UserEntity) entity).setRoleId(
generateAutoIncrement(entity.getClass().getName() + "-" + entity.getRole(), 1L));
}
mongoDataStore.save(entity);
return entity.getId();
}
/**
* Return a unique numeric value for the given key.
* The minimum value, set to 1 if nothing specific is required.
*/
protected long generateAutoIncrement(final String key, final long minimumValue){
// Get the given key from the auto increment entity and try to increment it.
final Query<AutoIncrementEntity> query = mongoDataStore.find(
AutoIncrementEntity.class).field("_id").equal(key);
final UpdateOperations<AutoIncrementEntity> update = mongoDataStore
.createUpdateOperations(AutoIncrementEntity.class).inc("value");
AutoIncrementEntity autoIncrement = mongoDataStore.findAndModify(query, update);
// If none is found, we need to create one for the given key.
if (autoIncrement == null) {
autoIncrement = new AutoIncrementEntity(key, minimumValue);
mongoDataStore.save(autoIncrement);
}
return autoIncrement.getValue();
}
And finally your entity:
#Entity(value = "user", noClassnameStored = true)
public class UserEntity extends BaseEntity {
public static enum Role {
ADMIN, USER,
}
private Role role;
#Indexed(unique = true)
private Long userId;
private Long roleId;
// Role setter and getter
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
}
There's nothing specific going on in the entity. All the logic is handled by the persistence service. I'm not using the #PrePersist, because you'd then need to put the persistence service into the entity, which doesn't sound like a good idea.

Custom code generation for JPA entities from database

I'm here asking for a simple way to add some custom code in the JPA Entity generated by Eclipse from database.
Basically what I want to achieve is to add public String properties containing the names of the entity properties, and use them when I need to provide "property name" as String and be sure that there won't be runtime access errors.
Something like this
#Entity
#Table(name="clients")
#NamedQuery(name="ClientModel.findAll", query="SELECT c FROM ClientModel c")
public class ClientModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="id_client")
private long idClient;
public String name;
public ClienteModel() {
}
public long getIdClient() {
return this.idClient;
}
public void setIdClient(long idClient) {
this.idClient = idClient;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//CUSTOM CODE
public static final String idClientProperty = "idClient";
public static final String nameProperty = "name";
}
So i could use property name like
ClientModel.nameProperty
and be compile-time safe of his existence and in case of names refactoring after a further entity generation.
I'm aware of the existence of Telosys Tools & co., but I hoped there could be something simplier/faster (like a custom class provided as plugin in WSDL_to_entity generation with JAXB)
Thank you.
In the end I've used Telosys Tools, even if I didn't want to add another tool to my project,
Is kinda easy to set up, just read here
https://sites.google.com/site/telosystools/getting-started/21-configure-a-project
In my specific case i've added to the template "JPA_bean_with_links" this code during getters creation
#if ( $field.getter ) public static String ${field.getter}Property() {
return "$field.name";
}
#end

Display only 1 field in Nested Object Metawidget

Using the metawidget to build some flexible UI in Java: https://sourceforge.net/projects/metawidget/
public class Cohort {
private int id;
private Project project;
private Member teamLead;
public Cohort() { }
#UiHidden
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Project getProject() { return project; }
public void setProject(Project project) { this.project = project; }
public Member getTeamLead() { return teamLead; }
public void setTeamLead(Member teamLead) { this.teamLead = teamLead; }
}
Cohort is the class inspected. However as is desirable it recursively inspects both the Project and Member classes.
When displayed on the UI, it will display all the fields for each of the classes. However I would only like to display the "Name" field of the Project and firstName + last Name of the Member.
There are a number of ways to achieve this. I'll start with one and let me know if it's sufficient for your needs:
a) mark the fields of Project/Member that you don't want to see as UiHidden (you don't say what those fields are, but you seem to have gotten the idea because you are already hiding 'Cohort.getId'). Note you can also reuse existing annotations (like JPA annotations) for this purpose.
b) mark 'Cohort.getProject' and 'Cohort.getTeamLead' as UiLabel( "" ). This will suppress the sub-label for the sub-object, and make its fields appear as if part of the original object.

Categories

Resources