在android studio中使用DataBase,如何创建DataBase?我如何在不同的活动中使用它?

时间:2014-12-07 19:57:44

标签: android database android-studio

我只是在项目的开始,我是堆栈! 这是一个学校项目,我需要创建一个应用程序,能够(理论上)从远处的餐馆订购,并通过它来简化订购和支付。 为此我需要使用数据库,我需要为餐馆建议的产品构建表格,表格为不同的类别用户表和预订表。 这些是每个表中的列:

    //product table columns
public static final String PRODUCT_KEY_ID = "id";
public static final String PRODUCT_KEY_NAME = "name";
public static final String PRODUCT_KEY_CATEGORY = "category";
public static final String PRODUCT_KEY_PRICE= "price";
public static final String PRODUCT_KEY_QUANTITY= "quantity";

//category table columns
public static final String CATEGORY_KEY_ID = "id";
public static final String CATEGORY_KEY_NAME = "name";

//users table columns
public static final String USERS_KEY_ID = "id";
public static final String USERS_KEY_NAME = "name";
public static final String USERS_KEY_PASSWORD = "password";
public static final String USERS_KEY_MAIL = "mail";

//reservation table columns
public static final String RESERVATION_KEY_ID = "id";
public static final String RESERVATION_KEY_USERID = "user";
public static final String RESERVATION_KEY_PRICE = "price";
public static final String RESERVATION_KEY_PAID = "is_it_paid";

如何构建我的数据库,以便每个Activity 在首次创建后能够访问它? **编辑:**我已经创建了" CREATE_TABLE_NAME"它是发送给SQL的String。

我在Main类中实现DataBase文件的onCreate时遇到了麻烦。我还需要以某种方式保存我的数据,以便我可以从另一个活动访问它(更新数据库并从中读取)。

非常感谢和抱歉这个长期的问题。 :)

1 个答案:

答案 0 :(得分:0)

查看API文档here。该示例为您提供了一个可以遵循的漂亮的类设计。 简短摘要:

  • 使您的班级成为SQLiteOpenHelper
  • 的子类
  • 覆盖onCreate(SQLiteDatabase db)
  • sql create statement
  • 上执行db

您可以使用您的上下文随处访问它。片段或活动:

// Create an instance of your SQLiteOpenHelper Subclass (in this case YourDB)
YourDB yourDB = new YourDB(this); // the parameter here is a context. (see the API example) 
SQLiteDatabase database = yourDB.getReadableDatabase(); // or: yourDB.getWriteableDatabse() for insert/delete/ update operations.
// do your stuff with the database
// ....
// and remember to close them:
yourDB.close();
database.close();

如果您创建新对象,Android运行时将不会创建完整的新数据库。

相关问题