Skip to content
Advertisement

How to insert multiple rows in a SQL Database

I’m developing a Recipes Book and I’ve a problem saving multiple Ingredients for the same Recipe in the database. I can add, pressing a button, multiples Linear Layout with inside an ingredient EditText and a quantity EditText. So the for cycle evaluates each Layout, it takes the currents ingredient and quantity values saving them in the newIngredient instance (of the Ingredient.class). Then it inserts the instance in the database and finally, it adds the instance to my “ingredients” ArrayList and closes the DB. With the debug, I found out that all this works only for the first iteration of for cycle.

Advertisement

Answer

In your code you are closing the database inside the for loop.

For this reason, your code will execute the first iteration, then close the database and so the next iterations will fail due to a closed db connection.

You should move your dbHeloper.close(); call outside the loop.

In addiction, you can move your variable outside the for loop, for a better memory usage. In shorts:

Step 1: close database after the loop cycle

Step 2: optimize variables

Hope this helps!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement