首页 > 解决方案 > 在 SQL 数据库的一行中插入 ArrayList

问题描述

在我的食谱日记中,我有 3 个课程,Recipe.class:

public Recipe(String title, String firstImage, String secondImage, String thirdImage, String instructions, int targetPeople, int time, int calories, ArrayList<Ingredient> ingredients, ArrayList<Tag> tags) {

    this.title = title;
    this.firstImage = firstImage;
    this.secondImage = secondImage;
    this.thirdImage = thirdImage;
    this.instructions = instructions;
    this.targetPeople = targetPeople;
    this.time = time;
    this.calories = calories;
    this.ingredients = ingredients;
    this.tags = tags;
}

成分类:

public Ingredient(String ingredient_name, int quantity) {

    this.ingredient_name = ingredient_name;
    this.quantity = quantity;
}

和标签类:

public Tag(String tag_name) {

    this.tag_name = tag_name;

}

当我保存一个新食谱时,我使用两个 for 循环来存储标签和成分,并将它们中的每一个都添加到相应的 ArrayList<> (将更多成分和标签链接到同一个食谱),如下所示:

for (int c=0; c < countTags; c++) {
           childChipView = (Chip) chipTagGroup.getChildAt(c);
           childTextViewTag = childChipView.findViewById(R.id.chip_item);
        childTag = childTextViewTag.getText().toString();
        newTag = new Tag(childTag);
        dbHelper.insertTag(newTag);
        tags.add(newTag);
    }

    // ingredients fields settings
    for (int d=0; d<countIngredients; d++) {
        childViewIng = parentIngredientLayout.getChildAt(d);
        childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
        childTextViewQ = childViewIng.findViewById(R.id.quantityField);
        childIngredient = childTextViewI.getText().toString();
        childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
        newIngredient = new Ingredient(childIngredient, childQuantity);
        dbHelper.insertIngredient(newIngredient);
        ingredients.add(newIngredient);
    }

之后,我存储在我的数据库的三个对应表中(RECIPE_TABLE、INGGREDIENT_TABLE、TAG_TABLE)。我的问题是,如何将两个 ArrayLists<> 存储在RECIPE_TABLE 中?我想要,即在该表的同一行中,标题、说明、时间、卡路里等以及两个 ArrayList

标签: androidsqldatabasearraylist

解决方案


您不应该在一行中插入整个数组,因为这违反了 1NF,请尝试将其拆分为 2 个表


推荐阅读