如何在Android中设置数据库(表)以在它们之间执行搜索

时间:2016-01-21 15:32:35

标签: android database sqlite recipe

修改

我了解到我可能不需要多个数据库,但该数据库中有多个表。

我现在拥有的 我正在构建一个将要处理食谱的应用程序。目前,我有一种储物柜,你可以在那里添加你想要的储物柜。例如,这可能是一包碎牛肉或一条面包或什么不是。我让用户在应用程序中添加它,具体取决于他们在储物柜/冰箱/冰柜中的含量。我这样做,使用SQLiteDatabase。一切都按我想要的方式工作,但现在,我想添加更多功能。

我想要实现的目标

好的,所以在我的应用程序中,我有一个搜索按钮。当用户想要搜索时,他应该能够输入一种成分(如碎牛肉),然后收到含有碎牛肉的食谱结果。他还应该能够搜索食谱,然后获得该食谱或类似于他输入的食谱。

场景1 。用户搜索成分。

应该发生什么用户应该获得包含该特殊成分的所有食谱的结果。当用户找到他喜欢的食谱时,他应该可以点击它,应用程序应该显示他在家里有什么成分以及他需要购买哪些成分。

场景2 。用户搜索或配方

应该发生什么。用户获得与其搜索匹配的食谱的结果。如果他点击一个,他应该显示的成分(如场景1中)和他需要购买的成分也应该显示,也如场景1中所示。

问题

我应该如何尽可能有效地(在执行时间方面)设置数据库,以便能够通过一次搜索显示来自不同数据库的信息。我发现这是http://www.databaseanswers.org/data_models/recipes/index.htm,我猜测我需要多个数据库。 我不需要帮助来编写设置阶段,而只需要设计数据库的结构。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您不需要拥有多个数据库来存储应用程序模型的对象。您可能需要考虑为您的应用程序使用以下(或类似的)域模型类,并在数据库中使用相应的表:

public class Recipe {
    int id;
    String name;
    String source; // Mom, A friend's name, A website url, a magazine name, etc.
    Date lastUpdated; // When the recipe was added/updated
    ArrayList<Ingredient> ingredients; // A list of ingredients used by this recipe 
}

public class Ingredient {
    int id;
    String name;
    String preferredSources; // a store name, a friend's name :), etc.
    ArrayList<Recipe> recipes; // A list of recipes which use this ingredient
}

public class RecipeIngredient { // Join class for many-to-many relationship
   int recipeId;
   int ingredientId;
}

public class Inventory {
    int ingredientId;
    int location; // locker, fridge, freezer, etc.
    float quantity; // in weight, count, etc.
    Date lastUpdated; // When the last replenishment was done
}

由于Recipe和Ingredient对象之间存在多对多关系,我建议创建一个连接类RecipeIngredient。库存类是针对您目前在家中的成分。

您的搜索可能会针对食谱和成分类(表格)进行。一旦您获得相应的成分ID,您可以在您的库存中搜索这些成分在家中的可用性。

购买Ingredient项目后,您应该更新Inventory类(表格)。此外,在成分用完后,您应该更新其库存数量。

为了简化开发工作,包括为您的应用创建自动数据库架构(表),您可以考虑使用JDXA之类的ORM。以下是一些用于处理与JDXA的多对多关系的code snippets