java - "No setter/field for field found on class"
问题描述
I'm creating an app in Android Studio, which connects to a Cloud Firestore database. In the database I have the following structure:
Myclass
- name = "test"
- subclass
- 0 = "String 1"
- 1 = "String 2"
The class itself is declared like this (irrelevant bits removed):
public class Myclass {
private String name;
private String[] subclass;
// CONSTRUCTOR
public Chart() {}
//GETTERS
public String getName() { return this.name; }
// SETTERS
public void setSubclass(String[] thisSubclass) { this.subclass = thisSubclass; }
}
In the activity, the Myclass object is set up like this (again, irrelevant bits removed):
public class MyclassActivity {
DocumentReference docRef;
Myclass myItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up database connection, read in itemId etc...
// ...omitted for clarity...
docRef = databaseRef.collection("myclass").document(itemId);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
myItem = document.toObject(Myclass.class);
}
}
}
}
This reads in the Myclass object, with the name set correctly, but the subclass object doesn't get set up - it's still null.
In the debug console there's the following message:
No setter/field for subclass found on class path.to.app.Myclass
The 'setSubclass' function is greyed out, as if it's never used. I'm sure the problem is something obvious, but I can't see it.
解决方案
您现在的问题是您的类名必须与构造函数相同。您还需要在参数中添加getter
一个subclass
。
public class Chart {
private String name;
private String[] subclass;
public Chart() {
//Default empty constructor, required for Firebase.
}
public Chart(String name, String[] subclass) {
this.name = name;
this.subclass = subclass;
}
public String getName() {
return this.name;
}
public String[] getSubclass() {
return subclass;
}
}
另一方面,您不需要添加设置器。它们不是必需的。Firebase 会将值设置到该字段中。但是,如果您要从外部与班级互动,则应该添加它们。
在某些情况下,您希望在参数上使用不同的名称,可能是因为您想遵循驼峰命名法或其他名称。如果是这种情况,您可以使用注释@PropertyName
在数据库中提供不同的名称,并根据需要保留模型。例如:
public class Chart {
@PropertyName("name")
private String mName;
@PropertyName("subclass")
private String[] mSubclass;
public Chart() {
}
@PropertyName("name")
public String getmName() {
return mName;
}
@PropertyName("subclass")
public String[] getmSubclass() {
return mSubclass;
}
}
推荐阅读
- java - Maven:“NoClassDefFoundError:com/jogamp/newt/event/KeyListener”
- neo4j - 使用密码投影的过程中不允许写入或令牌创建操作
- c# - 通过fast-mono-cgi运行asp.net,随机崩溃System.IO.DirectoryNotFoundException
- python - 谷歌云人才解决方案:如何使用 page_token
- r - R - 构建包时出错 - 无法安装到 srcdir
- c# - 如何在 C# 中解析 MTOM 肥皂响应
- phpunit - 在使用 PHPUnit 和 PhpStorm 进行测试时,是否可以在 localhost 上调试 API 请求?
- python - 从同级文件夹导入模块
- reactjs - 未在 HOST 中使用“localhost”进行 create-react-app 开发
- jasper-reports - 如何在生成的 PDF 文件中禁用打印选项?