繁体   English   中英

在Android Studio中使用数据库,如何创建数据库? 如何在不同的活动中使用它?

[英]Using DataBase in android studio, how do I create the DataBase? how do I use it in different Activities?

我只是在我的项目的开始,我就堆了! 这是一个学校项目,我需要创建一个应用程序,该应用程序(理论上)能够从远处的餐厅订购,并因此使订购和付款变得容易。 为此,我需要使用数据库,我需要为餐厅建议的产品构建表,为不同的CategoryUsers表和Reservations表构建表。 这些是每个表中的列:

    //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的字符串。

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

非常感谢,很抱歉提出这个问题。 :)

此处查看API文档。 该示例为您提供了不错的类设计,可以遵循。 简短摘要:

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

您可以使用上下文从任何地方访问它,例如片段或活动:

// 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运行时不会创建完整的新数据库。

暂无
暂无

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

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