#android #sql #database #arraylist
#Android #sql #База данных #список массивов
Вопрос:
В моем дневнике рецептов у меня есть 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;
}
Ingredient.class:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
и Tag.class:
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, INGREDIENT_TABLE, TAG_TABLE). Моя проблема в том, как я могу сохранить два списка массивов<> внутри RECIPE_TABLE? Я хочу, т. е. в той же строке этой таблицы, заголовок, инструкции, время, калории и т.д., А также два списка массивов
Комментарии:
1. По определению ArrayList будет другой таблицей в БД (с отношением «один ко многим») … конечно, вы можете сериализовать ArrayList и сохранить его как строку, но это было бы неудобно
2. Итак, вы предлагаете мне создать таблицу RECIPE_INGREDIENT и таблицу RECIPE_TAG, чтобы связать списки массивов с одним и тем же рецептом?
3.
RECIPES (ID, Name, ...)
TAGS(ID, Name,..)
INGREDIENTS(ID, Name,..)
RECIPE_TAGS(RecipeID, TagID)
RECIPE_INGREDIENTS(RecipeID, IngredientID)
… вот как большинство программистов сделали бы это с реляционной базой данных
Ответ №1:
Вы не должны вставлять весь массив подряд, потому что это нарушает 1NF, попробуйте разделить его на 2 таблицы