该文件怎么修改为数据存入数据库,并且Excel从数据库添加数据
时间: 2024-12-14 20:22:04 浏览: 1
要将 `BatteryDataService` 修改为将数据存入数据库,并通过数据库将数据导出到 Excel,你需要进行以下步骤:
### 1. 添加数据库支持
首先,需要在项目中引入 SQLite 数据库支持。Android 提供了 `SQLiteOpenHelper` 类来帮助管理数据库的创建和版本管理。
#### 1.1 创建数据库帮助类
创建一个新的类 `BatteryDatabaseHelper` 来管理数据库的操作:
```java
package com.example.powermanagement;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BatteryDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "BatteryData.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "BatteryData";
private static final String CREATE_TABLE_SQL =
"CREATE TABLE " + TABLE_NAME + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"SN TEXT," +
"Time TEXT," +
"Battery_Level INTEGER," +
"Current REAL," +
"Voltage REAL," +
"Temperature REAL," +
"VBUS REAL," +
"IBUS REAL," +
"Rsoc TEXT," +
"Charge_Type TEXT," +
"Charge_Status TEXT," +
"Full_Capacity INTEGER," +
"NTC_Temperature REAL" +
");";
public BatteryDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
### 2. 修改 `BatteryDataService` 以存储数据到数据库
修改 `BatteryDataService` 中的 `saveSingleDataToExcel` 方法,使其将数据存储到数据库中:
#### 2.1 引入数据库帮助类
在 `BatteryDataService` 中引入 `BatteryDatabaseHelper`:
```java
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
private BatteryDatabaseHelper dbHelper;
private SQLiteDatabase db;
@Override
public void onCreate() {
super.onCreate();
context = this;
handler = new Handler();
// 初始化 Runnable
runnable = new Runnable() {
@Override
public void run() {
Log.e("zhushiqi", "循环读取时间" + getCurrentTimestamp() + " 循环中读取电量" + getBatteryLevel());
// 采集数据
data = collectBatteryData();
// 存储数据到数据库
saveSingleDataToDatabase(data);
// 设置下次采集的时间间隔
handler.postDelayed(this, 1000); // 2000 毫秒为时间间隔
}
};
// 启动定时任务
handler.postDelayed(runnable, 1000); // 第一次延迟1000毫秒执行
// 注册关机广播接收器
IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
shutdownReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 关闭数据库连接
if (db != null) {
db.close();
Log.d("zsq", "ShutdownReceiver Database closed successfully.");
}
if (dbHelper != null) {
dbHelper.close();
Log.d("zsq", "DatabaseHelper closed successfully.");
}
}
};
registerReceiver(shutdownReceiver, filter);
// 初始化数据库
dbHelper = new BatteryDatabaseHelper(this);
db = dbHelper.getWritableDatabase();
}
```
#### 2.2 修改 `saveSingleDataToExcel` 方法
将 `saveSingleDataToExcel` 方法改为 `saveSingleDataToDatabase`:
```java
private void saveSingleDataToDatabase(BatteryData data) {
String sql = "INSERT INTO BatteryData (SN, Time, Battery_Level, Current, Voltage, Temperature, VBUS, IBUS, Rsoc, Charge_Type, Charge_Status, Full_Capacity, NTC_Temperature) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String formattedTime = dateFormat.format(data.getTime());
statement.bindString(1, data.getSN());
statement.bindString(2, formattedTime);
statement.bindLong(3, data.getLevel());
statement.bindDouble(4, data.getCurrent());
statement.bindDouble(5, data.getVoltage());
statement.bindDouble(6, data.getTemperature());
statement.bindString(7, data.getVBUS());
statement.bindString(8, data.getIBUS());
statement.bindString(9, data.getRsoc());
statement.bindString(10, data.getCharge_TYPE());
statement.bindString(11, data.getChargeStatus());
statement.bindLong(12, Long.parseLong(data.getFull_Capacity()));
statement.bindDouble(13, data.getTCP_tem());
statement.execute();
statement.clearBindings();
}
```
### 3. 从数据库导出数据到 Excel
创建一个新的方法 `exportDataToExcel` 来从数据库中读取数据并导出到 Excel 文件:
```java
private void exportDataToExcel() {
Cursor cursor = db.query("BatteryData", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Battery Data");
// 创建表头
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("SN");
header.createCell(1).setCellValue("Time");
header.createCell(2).setCellValue("Battery Level (%)");
header.createCell(3).setCellValue("Current (mA)");
header.createCell(4).setCellValue("Voltage (V)");
header.createCell(5).setCellValue("Temperature (°C)");
header.createCell(6).setCellValue("VBUS (µV)");
header.createCell(7).setCellValue("IBUS (µA)");
header.createCell(8).setCellValue("Rsoc");
header.createCell(9).setCellValue("Charge Type");
header.createCell(10).setCellValue("Charge Status");
header.createCell(11).setCellValue("Full_Capacity");
header.createCell(12).setCellValue("NTC_Temperature");
int rowNum = 1;
do {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(cursor.getString(cursor.getColumnIndex("SN")));
row.createCell(1).setCellValue(cursor.getString(cursor.getColumnIndex("Time")));
row.createCell(2).setCellValue(cursor.getInt(cursor.getColumnIndex("Battery_Level")));
row.createCell(3).setCellValue(cursor.getDouble(cursor.getColumnIndex("Current")));
row.createCell(4).setCellValue(cursor.getDouble(cursor.getColumnIndex("Voltage")));
row.createCell(5).setCellValue(cursor.getDouble(cursor.getColumnIndex("Temperature")));
row.createCell(6).setCellValue(cursor.getString(cursor.getColumnIndex("VBUS")));
row.createCell(7).setCellValue(cursor.getString(cursor.getColumnIndex("IBUS")));
row.createCell(8).setCellValue(cursor.getString(cursor.getColumnIndex("Rsoc")));
row.createCell(9).setCellValue(cursor.getString(cursor.getColumnIndex("Charge_Type")));
row.createCell(10).setCellValue(cursor.getString(cursor.getColumnIndex("Charge_Status")));
row.createCell(11).setCellValue(cursor.getLong(cursor.getColumnIndex("Full_Capacity")));
row.createCell(12).setCellValue(cursor.getDouble(cursor.getColumnIndex("NTC_Temperature")));
} while (cursor.moveToNext());
try {
File file = createExcelFile("BatteryData_" + getCurrentTimestamp() + ".xlsx");
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);
fileOutputStream.close();
workbook.close();
Toast.makeText(this, "Data exported to Excel successfully.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error exporting data to Excel: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No data to export.", Toast.LENGTH_SHORT).show();
}
cursor.close();
}
```
### 4. 调用导出方法
可以在适当的地方调用 `exportDataToExcel` 方法,例如在某个按钮点击事件中:
```java
Button exportButton = findViewById(R.id.export_button);
exportButton.setOnClickListener(v -> exportDataToExcel());
```
这样,你就完成了将数据存储到数据库并在需要时将其导出到 Excel 文件的功能。
阅读全文