android studio加上SQLite数据库实现点餐系统
时间: 2023-06-29 08:03:20 浏览: 161
要在Android Studio中使用SQLite来实现点餐系统,需要遵循以下步骤:
1. 创建一个新的Android Studio项目
2. 在app模块下的build.gradle文件中添加以下依赖项:
```
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
}
```
3. 创建一个SQLiteOpenHelper类,以帮助创建和管理数据库。在该类中,您需要定义表格和列,并实现onCreate()和onUpgrade()方法。
```java
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Order.db";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + OrderContract.OrderEntry.TABLE_NAME + " (" +
OrderContract.OrderEntry._ID + " INTEGER PRIMARY KEY," +
OrderContract.OrderEntry.COLUMN_NAME_ITEM + " TEXT," +
OrderContract.OrderEntry.COLUMN_NAME_PRICE + " TEXT)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + OrderContract.OrderEntry.TABLE_NAME;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
```
4. 在MainActivity中使用DBHelper类来创建和操作数据库。您可以使用以下代码插入数据:
```java
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OrderContract.OrderEntry.COLUMN_NAME_ITEM, "Pizza");
values.put(OrderContract.OrderEntry.COLUMN_NAME_PRICE, "10");
db.insert(OrderContract.OrderEntry.TABLE_NAME, null, values);
```
5. 使用Cursor和Adapter来显示数据。您可以使用以下代码从数据库中检索数据:
```java
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {
OrderContract.OrderEntry._ID,
OrderContract.OrderEntry.COLUMN_NAME_ITEM,
OrderContract.OrderEntry.COLUMN_NAME_PRICE
};
Cursor cursor = db.query(
OrderContract.OrderEntry.TABLE_NAME,
projection,
null,
null,
null,
null,
null
);
int[] views = {R.id.item_name, R.id.item_price};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item_layout, cursor, projection, views, 0);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
```
以上是使用SQLite实现点餐系统的基本步骤。您可以根据自己的需求进行修改和扩展。
阅读全文