【问题标题】:Firebase Error: Expected a List, but got a class java.util.HashMapFirebase 错误:需要一个列表,但有一个类 java.util.HashMap
【发布时间】:2021-01-18 13:04:37
【问题描述】:

我有一个名为 Garage 的对象,一旦我第一次声明他,它就有 4 个参数:garageNamegarageIdgarageCoordinatorPhonegarageProducts。我把它上传到firebase。一段时间后,我更新了 firebase 中的garage 参数:garageStocks。 当我尝试将数据传回Garage 类时,我得到了例外:

com.google.firebase.database.DatabaseException:反序列化时需要一个列表,但得到了一个类 java.util.HashMap

我在Expected a List while deserializing, but got a class java.util.HashMap看到了一个几乎完全一样的问题:@

但它的答案对我来说没有意义......即使使用对象列表,我也能够获得值(参见 garageProducts)。

车库活动:

public class GaragesActivity extends AppCompatActivity {

    ArrayList<String> garages = new ArrayList<>();
    DatabaseReference dbReference = FirebaseDatabase.getInstance().getReference();
    RecyclerView rvGarages;
    Button tvGarageEdit;
    TextView tvGarageCoordinator;
    User selectedGarageCoordinator = null;
    boolean isEditable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_garages);

        
        //defines the widgets
        rvGarages = findViewById(R.id.rvGarages);
        tvGarageEdit = findViewById(R.id.tvGarageEdit);

        refreshAllGarages();

        //defines and sets the toolbar in place.
        Toolbar toolbar = findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        //defines the back button at the top corner
        ActionBar ab = getSupportActionBar();
        if(ab != null)
            ab.setDisplayHomeAsUpEnabled(true);


        tvGarageEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //the opposite every press
                if (isEditable){
                    isEditable = false;
                    tvGarageEdit.setBackgroundColor(getResources().getColor(R.color.colorWritingImportant));
                }else{
                    isEditable = true;
                    tvGarageEdit.setBackgroundColor(getResources().getColor(R.color.colorLimeGreen));
                }
            }
        });
    }
    
    private void refreshAllGarages() {
        //reset
        garages.clear();
        GaragesAdapter myAdapter = new GaragesAdapter(GaragesActivity.this, garages);
        rvGarages.setAdapter(myAdapter);

        final Dialog myDialog = new Dialog(GaragesActivity.this);
        myDialog.setContentView(R.layout.dialog_progress);
        if(myDialog.getWindow() != null)
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        TextView tvAction = myDialog.findViewById(R.id.tvAction);
        tvAction.setText("טוען...");
        myDialog.show();

        // Read from the database
        Query q = dbReference.child("מחסנים").orderByKey();
        q.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot AllGarages : dataSnapshot.getChildren()) //gets the list of Garages
                {
                    Garage g = AllGarages.getValue(Garage.class);
                    if(g.getGarageName() != null)
                        garages.add(g.getGarageName());
                }
                GaragesAdapter myAdapter = new GaragesAdapter(GaragesActivity.this, garages);
                rvGarages.setLayoutManager(new GridLayoutManager(GaragesActivity.this,4));
                myDialog.dismiss();
                rvGarages.setAdapter(myAdapter);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                throw databaseError.toException(); //Don't ignore errors
            }
        });

    }
}

车库类:

public class Garage {

    private String garageName;
    private String garageId;
    private String garageCoordinatorPhone;
    private ArrayList<Product> garageProducts;
    private ArrayList<Product> borrowedProducts;
    private ArrayList<Product> damagedProducts;
    private ArrayList<Product> missingProducts;
    private ArrayList<Stock> garageStocks;

    public Garage(){}

    public Garage(String garageName, String garageCoordinatorPhone, String garageId, ArrayList<Product> garageProducts){
        this.garageProducts = garageProducts;
        this.garageName = garageName;
        this.garageCoordinatorPhone = garageCoordinatorPhone;
        this.garageId = garageId;
    }

    public Garage(String garageName, String garageCoordinatorPhone, String garageId, ArrayList<Product> garageProducts, ArrayList<Stock> garageStocks){
        this.garageProducts = garageProducts;
        this.garageStocks = garageStocks;
        this.garageName = garageName;
        this.garageCoordinatorPhone = garageCoordinatorPhone;
        this.garageId = garageId;
    }

    public Garage(String garageName, String garageCoordinatorPhone, String garageId, ArrayList<Product> garageProducts, ArrayList<Stock> garageStocks, ArrayList<Product> borrowedProducts){
        this.garageProducts = garageProducts;
        this.garageStocks = garageStocks;
        this.garageName = garageName;
        this.garageCoordinatorPhone = garageCoordinatorPhone;
        this.garageId = garageId;
        this.borrowedProducts = borrowedProducts;
    }

    public Garage(String garageName, String garageCoordinatorPhone, String garageId, ArrayList<Product> garageProducts, ArrayList<Stock> garageStocks, ArrayList<Product> borrowedProducts, ArrayList<Product> damagedProducts, ArrayList<Product> missingProducts){
        this.garageProducts = garageProducts;
        this.garageStocks = garageStocks;
        this.garageName = garageName;
        this.garageCoordinatorPhone = garageCoordinatorPhone;
        this.garageId = garageId;
        this.borrowedProducts = borrowedProducts;
        this.damagedProducts = damagedProducts;
        this.missingProducts = missingProducts;
    }
}

火力基地:

{
  "173baaa74c0" : {
    "garageCoordinatorPhone" : "0523122548",
    "garageId" : "173baaa74c0",
    "garageName" : "רעננה מרכז",
    "garageProducts" : [ {
      "description" : "אורך 1.7 מטר",
      "productAmount" : 5,
      "productCategory" : "בנייה מחנאית",
      "productId" : 201,
      "productName" : "בזנט"
    }, {
      "description" : "נפח 500 סמ'ק",
      "productAmount" : 5,
      "productCategory" : "כיבוי אש",
      "productId" : 402,
      "productName" : "מטפים תקינים"
    }, {
      "description" : "אורך 30 ס'מ",
      "productAmount" : 4,
      "productCategory" : "כלי עבודה",
      "productId" : 506,
      "productName" : "שפכטל"
    }, {
      "description" : "אורך 30 ס'מ",
      "productAmount" : 1,
      "productCategory" : "חשמל",
      "productId" : 323,
      "productName" : "DI"
    }, {
      "description" : "סיר מתכת לטיולים, קוטר 15 ס'מ",
      "productAmount" : 7,
      "productCategory" : "בישול",
      "productId" : 127,
      "productName" : "סיר בינוני"
    }, {
      "description" : "",
      "productAmount" : 1,
      "productCategory" : "חשמל",
      "productId" : 309,
      "productName" : "מיקרופון"
    } ],
    "garageStocks" : {
      "1610831472776" : {
        "stockFillerPhone" : "0544926410",
        "stockId" : 1610831472776,
        "stockProducts" : [ {
          "description" : "אורך 1.7 מטר",
          "productAmount" : 5,
          "productCategory" : "בנייה מחנאית",
          "productId" : 201,
          "productName" : "בזנט"
        }, {
          "description" : "נפח 500 סמ'ק",
          "productAmount" : 5,
          "productCategory" : "כיבוי אש",
          "productId" : 402,
          "productName" : "מטפים תקינים"
        }, {
          "description" : "אורך 30 ס'מ",
          "productAmount" : 4,
          "productCategory" : "כלי עבודה",
          "productId" : 506,
          "productName" : "שפכטל"
        }, {
          "description" : "אורך 30 ס'מ",
          "productAmount" : 1,
          "productCategory" : "חשמל",
          "productId" : 323,
          "productName" : "DI"
        }, {
          "description" : "סיר מתכת לטיולים, קוטר 15 ס'מ",
          "productAmount" : 7,
          "productCategory" : "בישול",
          "productId" : 127,
          "productName" : "סיר בינוני"
        }, {
          "description" : "",
          "productAmount" : 1,
          "productCategory" : "חשמל",
          "productId" : 309,
          "productName" : "מיקרופון"
        } ]
      }
    }
  },
  "1740c8d4920" : {
    "garageCoordinatorPhone" : "0544926411",
    "garageId" : "1740c8d4920",
    "garageName" : "אשדוד ט'ו",
    "garageProducts" : [ {
      "description" : "",
      "productAmount" : 2,
      "productCategory" : "שונות",
      "productHome" : "173baaa74c0",
      "productId" : 1102,
      "productName" : "דרבוקות גדולות"
    }, {
      "description" : "נפח 500 סמ'ק",
      "productAmount" : 2,
      "productCategory" : "כיבוי אש",
      "productHome" : "173baaa74c0",
      "productId" : 402,
      "productName" : "מטפים תקינים"
    } ]
  },
  "174534895e0" : {
    "borrowedProducts" : {
      "5f66189e 207aeaca" : [ {
        "description" : "סיר מתכת לטיולים, קוטר 15 ס'מ",
        "productAmount" : 1,
        "productCategory" : "בישול",
        "productHome" : "173baaa74c0",
        "productId" : 127,
        "productName" : "סיר בינוני"
      } ]
    },
    "garageCoordinatorPhone" : "0544926410",
    "garageId" : "174534895e0",
    "garageName" : "הכפתור",
    "garageProducts" : [ {
      "description" : "אורך 1.7 מטר",
      "productAmount" : 23,
      "productCategory" : "בנייה מחנאית",
      "productHome" : "173baaa74c0",
      "productId" : 201,
      "productName" : "בזנט"
    }, {
      "description" : "",
      "productAmount" : 2,
      "productCategory" : "שונות",
      "productHome" : "173baaa74c0",
      "productId" : 1102,
      "productName" : "דרבוקות גדולות"
    }, {
      "description" : "נפח 500 סמ'ק",
      "productAmount" : 1,
      "productCategory" : "כיבוי אש",
      "productHome" : "173baaa74c0",
      "productId" : 402,
      "productName" : "מטפים תקינים"
    } ]
  }
}
enter code here

【问题讨论】:

  • 上传整个车库活动以便更好地参考
  • 您在问题中包含了 JSON 树的图片。请将其替换为实际的 JSON 作为文本,您可以通过单击 your Firebase Database console 的溢出菜单 (⠇) 中的 Export JSON 链接轻松获取。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。

标签: android firebase firebase-realtime-database


【解决方案1】:

根据您的 Firebase JSON,您似乎正在存储一个 object,其中每个 Stock 的字段都在 garageStocks 中,而不是像 Garage 类所期望的列表。 p>

例如,您有:

"garageStocks" : {
  "stockObject1": { ... },
  "stockObject2": { ... },
  ...
}

但是,您的 Garage 类需要一个列表:private ArrayList&lt;Stock&gt; garageStocks;,它在 JSON 中应该是以下内容:

"garageStocks": [
  { stock object 1 },
  { stock object 2 },
  ...
]

这就是为什么你会收到错误,它需要一个列表,而是得到一个地图。

要解决此问题,您有几个选择:

  1. 更改将数据推送到 Firebase 的方式,以确保您推送的是列表
  2. garageStocks 的类型更改为HashMap

我不知道您目前正在为选项 1 做什么,但您似乎在为 Garage 类中的产品列表 (ArrayList&lt;Product&gt;) 做正确的事情,所以这可能是一个好地方去看看。

希望这会有所帮助!

【讨论】:

  • 查看我在ArrayList&lt;Product&gt; 案例中的表现的建议很有帮助!我改变了它,所以代码推送一个列表而不是其他任何东西!
猜你喜欢
  • 1970-01-01
  • 2021-08-24
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2017-10-17
  • 2021-07-08
  • 2017-10-11
相关资源
最近更新 更多