简体   繁体   English

Android Studio-向SQLite数据库添加不同的数据

[英]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. 已经可以在我的SQLite数据库中存储新配方,并在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 例如,我需要一个蛋糕:1个苹果2个鸡蛋

but for a cookie: 1 chocolate 1 egg 3 smarties 但要使用饼干:1巧克力1鸡蛋3聪明人

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 马丁

创建具有其属性的配料表,然后创建交叉引用表(用于多对多关系),您可以在其中将配料链接到配方以及其他信息(如所需量)。

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 1-根据需要添加任意数量的列,但是如果不需要,则存储空值,然后检查是否不为空

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 2.-另一个只是创建一个包含所有成分的大串并将其存储在1列中

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获取每个令牌,在这种情况下为“ *”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM