在列表中整理 Android 领域数据

Organize Android Realm data in lists

我正在考虑将我们当前的应用程序迁移到领域,并试图找出将数据组织到领域的最佳方式。对于这个问题,我将重点关注我的数据模型的 Photo 对象(但还有其他对象)。

我所有的数据对象都来自 API,其端点例如:getPopular()getNearbyPhotos(lat, lng)getUserPhotos(userId)getAlbumPhotos(albumId)getCollection(type).在大多数这些端点上还有其他参数,例如 sort=best/chronological.

我们目前在项目中使用 this non-relational DB,它允许仅使用 listName 对对象列表进行排序和检索。我们使用 listName 作为端点+参数的组合。

Realm(作为关系数据库)使用标准查询,例如:

realm.where(User.class)
     .contains("name", "Doe")
     .findAll();

当所有数据都在本地可用时,它工作正常,但这里的问题是这些查询的大量数据保存在服务器端,从未发送到客户端。例如,Photo 模型既不包含位置也不包含 best 排序的分数。

在我当前的测试项目中,我正在通过创建一个类似于我们当前项目使用对象的 ListPhoto 来解决这个问题:

public class ListPhoto extends RealmObject {
   @PrimaryKey public String id;
   public RealmList<Photo> list;
}

并使用实际的 API 端点和参数作为 id。所以我可以通过简单的查询找到这些对象

ListPhoto listPhoto = realm
          .where(ListPhoto.class)
          .equalTo("id", id)
          .findFirst();

但是通过这种方法,我创建了一个额外的抽象层来简单地存储分组和排序元数据,我对此并不满意,我在这里问一下:

我如何才能仅根据插入的顺序和组在领域中查询数据,而不使用我想出的这个肮脏的 hack?

编辑:

后续问题:

But because it's data that is never visually presented to the user, it is not sent to the client (I would like to migrate to Realm, but would be better to do it without having to change server-side data models and endpoit behaviors)

虽然可怜,但可以理解

你能做的就是给你的领域 Photo 对象提供字段,比如

public class Photo extends RealmObject {
    // other fields

    private double latitude;
    private double longitude;
    private String score;
}

然后,您像现在一样使用 API 端点和参数查询服务器。

当结果出现时,您将它们存储在领域中,并为它们分配 lat/long/score 的值。您此时可以使用这些,因为您刚刚在服务器查询中使用了它们。

所以如果你查询 api/getNearbyPhotos(1, 2)?sort=best:
(伪代码)

api.fetch("getNearbyPhotos(1, 2)?sort=best", new GetPhotoCompleteListener {
    @Override
    void onSuccess(List<Photo> photos) {
        // assuming gson or something has already parsed the server response into photo objects
        for (Photo p : photos) {
            p.setLatitude(1);
            p.setLongitude(2);
            p.setScore("best");
        }
        realm.copyToRealmOrUpdate(photos);
    }
}

现在你在领域中有了一堆照片对象,你可以像在服务器上那样查询它们。