You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Firestore报错:HashMap无法转换为Object类问题求助

Fixing the "HashMap cannot be cast to Object" Error in Firestore Data Retrieval

Hey there, let's break down why you're hitting this casting error and fix it step by step.

The Root Cause

When you call document.get("shoppingLists"), Firestore doesn't automatically convert the array of objects in your document into instances of your ShoppingListObject class. Instead, it deserializes each list item into a HashMap<String, Object> that maps Firestore field names to their values. Trying to directly cast this entire list to ArrayList<ShoppingListObject> is invalid—this is exactly why you're seeing the "HashMap cannot be cast to Object" error.

The Solution: Convert Raw Data Manually

Instead of forcing a cast, we'll iterate over the raw list of HashMaps from Firestore and convert each one into a ShoppingListObject instance. Here's your updated method:

private void getWholeListObject(int i, SellerObject soa) { 
    String userid = FirebaseAuth.getInstance().getCurrentUser().getUid(); 
    DocumentReference docRef = db.collection("Users").document(userid); 

    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { 
        @Override 
        public void onComplete(@NonNull Task<DocumentSnapshot> task) { 
            if (task.isSuccessful()) { 
                DocumentSnapshot document = task.getResult(); 
                if (document.exists()) {
                    // Fetch the raw list of HashMaps from Firestore
                    List<HashMap<String, Object>> rawShoppingLists = (List<HashMap<String, Object>>) document.get("shoppingLists");
                    ArrayList<ShoppingListObject> shoppingLists = new ArrayList<>();

                    // Convert each HashMap to a ShoppingListObject
                    for (HashMap<String, Object> rawItem : rawShoppingLists) {
                        ShoppingListObject listObj = new ShoppingListObject();
                        
                        // Set the listname (cast to String since Firestore stores it as a string)
                        listObj.setListname((String) rawItem.get("listname"));
                        
                        // Convert the products list from raw objects to Strings
                        List<Object> rawProducts = (List<Object>) rawItem.get("products");
                        ArrayList<String> products = new ArrayList<>();
                        for (Object product : rawProducts) {
                            products.add((String) product);
                        }
                        listObj.setProducts(products);
                        
                        shoppingLists.add(listObj);
                    }

                    // Now you can safely access the shoppingLists array
                    Log.i("asdf", "addNewDataToList: " + shoppingLists.get(i).getProducts()); 
                    addNewDataToList(i, shoppingLists, soa); 
                }
            } else {
                // Don't leave failure cases empty! Log the error for debugging
                Log.e("Firestore Error", "Failed to fetch user document", task.getException());
            }
        } 
    }); 
}

Important Checks & Tips

  • Field Name Consistency: Make sure the field names in your ShoppingListObject (listname, products) exactly match the field names in your Firestore document. Mismatched names will lead to null values.
  • Null Safety: I added a document.exists() check to avoid null pointer exceptions if the user document doesn't exist. You should also add null checks for rawShoppingLists and individual fields if your Firestore data might have missing values.
  • Error Handling: Filling in the else block with error logging will help you quickly diagnose issues like network failures or permission errors.

内容的提问来源于stack exchange,提问作者Markus Gerlach

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:06:42