Iterate over a BackendlessCollection and update

Hello,

I want to fetch some items from a table (“UserLevel”), iterate through them and add a new field. Below is my code. The error message that I get is

“Type:“java.lang.ClassCastException”, Description:“com.mypackage.UserLevel cannot be cast to java.util.Map”, ExceptionClass:“ServiceException” {Msg:“none”, Cause:“none”}”

Isn’t the BackendlessCollection a collection of Map items, each representing the columns (key/value) in the UserLevel table?

Also, am I right in assuming that the default column “created” corresponds to a LocalDate java type?

public void formatDate() {
        
        QueryOptions queryOptions = new QueryOptions(10, 0, "rating DESC");
        BackendlessDataQuery dataQuery = new BackendlessDataQuery(queryOptions);
        BackendlessCollection<Map> userLevels = Backendless.Data.of((Class)
        UserLevel.class).find(dataQuery);
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
        
        Iterator<Map> iterator = userLevels.getCurrentPage().iterator();
        
        while (iterator.hasNext()) {
            Map userLevelMap = iterator.next();
            LocalDate d = (LocalDate)userLevelMap.get("created");
            userLevelMap.put("createdFormatted", d.format(formatter));
            Backendless.Persistence.of("UserLevel").save(userLevelMap);
        }
    }

Maybe I should mention that since there is no “UserLevel class” in the Java sense, I can’t cast to “UserLevel” (on line 10). UserLevel is a table and it seems a little far fetched having to create a class for it just for the purpose of being able to iterate over the items.

I’m suspecting that there is a much easier way of doing what I want…

If there is no UserLevel class, the following line of code would not compile as it references UserLevel.class:

BackendlessCollection<Map> userLevels = Backendless.Data.of((Class) UserLevel.class).find(dataQuery);

To avoid creating a class representing objects from Backendless table, you should use the approach from the documentation referenced as “Using Java Map”, in that case, the argument for the “of” method must be a string which is the name of the table:

BackendlessCollection<Map> userLevels = Backendless.Data.of("UserLevel").find(dataQuery);

Hope this helps.

Mark

I realize that I was not clear in my description. The function in my original post exists in a class named “UserLevel” but the class could be called anything (maybe UserLevelService is more appropriate). However, changing according to your suggestion did the trick and after changing LocalDate to Date (wich seems to be the corresponding java class of the default field “created”) I got the result I wanted.

Thanks!