为嵌套数组的 Android 空间手动创建外键

Manually creating a foreign key for Android room for a nested array

我的 json 回复是:

{
    "categories": [
        {
            "categoryName": "Events",
            "entityId": "QwN9goUaw6",
             .....
        }
    ],
    "entityId": "T1nnwwpjOM"
}

我最初的计划是遵循 Google 在他们的 GithubSampleBrowser 中的做法,除了他们使用 StringUtil 方法从 List Integer 更改为 List String,所以我决定改变策略并尝试遵循一些其他人在这里说过将其转换为字符串并返回到 ArrayList。

我认为我有我最终想要做的正确查询,即

@Query("SELECT * FROM category_table WHERE entityId in (:entityId) ORDER BY sortIndex ASC")
public abstract LiveData<List<Category>> loadById(List<String> entityId);

我的模型目前看起来像:

类别搜索结果

@NonNull
@PrimaryKey
private String entityId;
@Nullable
private String query;
public List<Category> categories;
private String lastUpdated;

类别

@NonNull
@PrimaryKey(autoGenerate = true)
private int id;
private Integer sortIndex;
private String storyboardId;
@NonNull
private String entityId;
private String categoryName;
private String menuId;

我对转换器的尝试:

@TypeConverter
public static List<Category> fromStringToCategory(String value) {
    if (value != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        List<Category> categoryList = gson.fromJson(value,type);
        return categoryList;
    }
    return null;
}

@TypeConverter
public static String fromCategoryToString(List<Category> categories) {
    if (categories != null) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<Category>>() {
        }.getType();
        String json = gson.toJson(categories, type);
        return json;
    }
    return null;
}

我认为可能更容易的是生成 categorySearchResult 类别部分的 entityId 列表并在它们之间建立 @Relationship。我查看了有关用户和宠物的 android 文档,但无法将其与我的数据正确关联,因此非常感谢任何建议。

最后我将它们分开并通过将查询作为主键,它似乎也接受了一个我不确定的空白查询,它会允许它覆盖。然后我简单地使用 in 函数对 delete 进行了反向操作,可能可以处理为级联删除建立的关系,但就目前而言,它似乎工作得相当好。

综上所述

每当我的 mutablelivedata 发生变化时,它都会使用该查询传递到我的 CategorySearchResult,后者将基于该列表的实体 ID 带回。然后我像往常一样将类别单独放在自己的 class 中。