首页 > 解决方案 > "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.

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


您现在的问题是您的类名必须与构造函数相同。您还需要在参数中添加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;
   }
}

推荐阅读