要解决Android Studio中DatabaseHelper类无法正常工作的问题,可以尝试以下方法:
示例代码:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据库表
db.execSQL("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库版本升级时的操作
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
示例代码:
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
// 查询数据
Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
// 处理查询结果
}
cursor.close();
}
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "John");
long rowId = db.insert("mytable", null, values);
// 更新数据
ContentValues updateValues = new ContentValues();
updateValues.put("name", "Jane");
int rowsAffected = db.update("mytable", updateValues, "id=?", new String[]{"1"});
db.close();
示例代码:
示例代码:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_PATH = "/data/data/com.example.myapp/databases/";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// 拷贝数据库文件到默认位置
copyDatabase(context);
}
private void copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DATABASE_NAME);
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 其他代码省略
}
通过以上方法,您可以尝试解决Android Studio中DatabaseHelper类无法正常工作的问题。