martin-
martin-

Reputation: 23

Android Studio - Adding different data to SQLite Database

I´m working on a cookbook app. It´s already possible to store new recipes in my SQLite database and show them in a ListView. But now I´m trying to add the possibility to add the required ingredients and how much you need of them for the recipe. For different recipes there will be different amounts of ingredients required.

For example for a cake I need: 1 apple 2 eggs

but for a cookie: 1 chocolate 1 egg 3 smarties

For now I store fixed data (name, description, cooking time) in my database. But with the ingredients I think I will need a variable way to store them. I hope you get what my problem is. Is there a way to store these variable Objects in my database?

Martin

Upvotes: 0

Views: 779

Answers (2)

Carlos Carrizales
Carlos Carrizales

Reputation: 2340

well, you can use whatever of this ways to add your app:

1- Add as much columns as you need, but if you don't need one, just store empty value, later check if isn't empty

ContentValues contentValues = new ContentValues(); 
                            contentValues.put("ingredient1", Et1.getText().toString()); // string containing 2 eggs
                            contentValues.put("ingredient2", Et2.getText().toString()); // string containing 2 apples
                            contentValues.put("ingredient3", Et3.getText().toString().trim()); //string containing 1 chocolate
                            db.insert(TABLE_NAME, null, contentValues); //

2.- Another one is just to create a large string of all ingredients and store it in 1 column

String data ="";
                    data="2 eggs"+"*"+"1 chocolate "+"*"+"5 apples";
                    ContentValues contentValues = new ContentValues(); // 
                    contentValues.put("column1", data); // string containing 2 eggs
                    db.insert(TABLE_NAME, null, contentValues); // 

after that, use a stringTokenizer to get every token, in this case "*"

StringTokenizer st = new StringTokenizer(data,"*");
While(st.hasMoreTokens()){
    String aux = st.nextToken()// do somethig like show or replace with this
}

Upvotes: 0

datiKaa
datiKaa

Reputation: 326

Create a table for the ingredients with their attributes, than create a cross-reference table (for many-to-many relation) where you can link the ingredients to recipes with additional information like the needed amount.

Upvotes: 1

Related Questions