如何为我的SQLite配方表创建多个条目?

时间:2015-04-08 19:32:48

标签: android sqlite android-sqlite

在这里完成Android新手。所以我正在为我的班级制作一个食谱数据库,我想要一个"按成分搜索"该应用程序的选项。但是,当我的listview从数据库中提取所有成分时,它们不是单独的,而是根据配方聚集在一起。

这是我的DB代码:

String sql = "CREATE TABLE IF NOT EXISTS recipe (" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "Name TEXT, " +
            "Ingredients TEXT, " +
            "Recipe TEXT )";
    db.execSQL(sql);


    //This is the content for the Recipes. AKA the database
    ContentValues values = new ContentValues();

    values.put("Name", "Baked Eggcado");
    values.put("Ingredients",
            "Avacado" +
            "Egg" +
            "Salt" +
            "Pepper");

    values.put("Recipe",
            "\n" +
            "Prep Time: 5 minutes\n" +
            "\n" +
            "Cook Time: 15 to 20 minutes\n" +
            "\n" +
            "Total Time: 25 minutes\n" +
            "\n" +
            "Servings: 1\n" +
            "\n" +
            "Ingredients:\n" +
            "\n" +
            "1 avocado\n" +
            "\n" +
            "1 egg\n" +
            "\n" +
            "Salt and pepper to taste\n" +
            "\n" +
            "Directions:\n" +
            "\n" +
            "1. Preheat oven to 425°F.\n" +
            "\n" +
            "2. Slice avocado in half.\n" +
            "\n" +
            "3. Scoop out pit to create hole for the egg.\n" +
            "\n" +
            "4. Place avocado in a small baking cup. Line with tinfoil for minimal clean­up.\n" +
            "\n" +
            "5. Crack the egg into the hole.\n" +
            "\n" +
            "6. Bake for 15 to ­20 minutes.\n" +
            "\n" +
            "7. Season with salt and pepper, or seasoning of your choice. If you have them, sprinkle \n" +
            "\n" +
            "chopped scallions on top");
    db.insert("recipe", "Name", values);

所以我的问题是,如何让listview显示" Avacado"," Egg"," Salt",& "辣椒"单独而不是全部在一个单元格中。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

您将成分保存为单个文本项,因此,当您从数据库中读取它们并将它们放入列表项时,只有一个项目。

您需要添加某种分隔符,例如逗号,以允许您将从数据库读回的字符串拆分为字符串数组。这样,您可以轻松地将其作为单独的条目添加到列表中。

例如:

String[] ingredients = stringReadFromDatabase.split(",");

这将返回一个字符串数组,每个字符串中都包含一个项目。我没有使用空格作为分隔符,所以你仍然可以使用1/2杯糖等成分。

答案 1 :(得分:0)

问题是您使用" +"将所有食谱值连接在一个字符串中。所以对于Recipe键来说就是给出这样的价值             "准备时间:5分钟             烹饪时间:15至20分钟             总时间:25分钟"
因此...

key_is :"Recipe"
value_is:  "Prep Time: 5 minutes Cook Time: 15 to 20 minutes Total Time: 25 minutes"

对于您的预期结果,您必须以不同的结构保存数据。遵循通用JSon结构来保存您的数据。

{
       "Recipe":{
            "Prep Time": "5 minutes",
            "Cook Time": "15 to 20 minutes",
            "Total Time": "25 minutes"  
        }
}