在尝试插入子表之前未插入父表-android room

ttisahbt  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(196)

所以我有三张table,食谱,配料和配料。当插入一个新的配方,我插入一个配方,然后插入相应的新成分。当我尝试创建多对多关系时,我还获取每个新配方和配料的id,同时插入一个新配方和配料。我担心在插入配方配料之前,我没有完全插入配方和配料,因此我收到以下错误:

android.database.sqlite.SQLiteConstraintException: FOREIGN KEY constraint failed (code 787 SQLITE_CONSTRAINT_FOREIGNKEY)

下面是我创建插入所有信息的按钮时的代码。请注意,我使用循环插入每个新成分,并通过编辑文本从用户处获取输入值:

Recipe newRecipe = new Recipe(newRecipeTitle, newRecipeInstructions, newRecipeRating);

        recipeViewModel.insertRecipe(newRecipe);

        try {
            Thread.sleep(500);
            recipeId = newRecipe.getId();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String Ingredients[] = newRecipeIngredients.split(("\\r?\\n"));
        for(String ingredient : Ingredients){
            Log.d("this","newRecipe: " + Ingredients.length);

            Ingredients newIngredient = new Ingredients(ingredient);

            ingredientViewModel.insertIngredients(newIngredient);

            try {
                Thread.sleep(500);
                ingredientId = newIngredient.getId();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Log.d("this", "newRecipe: " + recipeId + ingredientId);
            recipeIngredientsViewModel.insert(new RecipeAndIngredients(recipeId,ingredientId));

        }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题