我是Android开发的新手,想要使用Assets文件夹中的csv文件创建和预填充SQLite数据库。我正在使用数据库适配器类,并在创建数据库后的onCreate方法中,我想从assets文件夹中读取csv文件,并使用它来使用DatabaseUtils.InsertHelper插入行。
import android.database.DatabaseUtils.InsertHelper;
//...
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
// need to read the path csv data here containing columns "_id" and "path"
try {
InputStream is = getAssets().open("pathcsv");
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
// Create a single InsertHelper to handle this set of insertions.
InsertHelper ih = new InsertHelper(db, "path_table");
// Get the numeric indexes for each of the columns that we're updating
final int id_Column = ih.getColumnIndex("_id");
final int path_Column = ih.getColumnIndex("path");
while (moreRowsToInsert) {
// ... Create the data for this row (not shown) ...
// Get the InsertHelper ready to insert a single row
ih.prepareForInsert();
// Add the data for each column
ih.bind(id_Column, idData);
ih.bind(path_Column, pathData);
// Insert the row into the database.
ih.execute();
}
}
//...
}
我在getAssets()行上遇到了一个日食错误:
-The method getAssets() is undefined for the type DatabaseHelper
我似乎无法让上下文工作,任何帮助都会受到赞赏。
更新
我应该包含所有代码,即:
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PATH_TABLE_CREATE);
try {
InputStream is = getAssets().open("@string/path");
// the rest is as in my first post above....
如果我按如下方式添加上下文,则会收到错误:
private static class DatabaseHelper extends SQLiteOpenHelper {
private Context myContext;
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);}
@Override
public void onCreate(SQLiteDatabase db, Context context) {
db.execSQL(PATH_TABLE_CREATE);
myContext = context;
try {
InputStream is = myContext.getAssets().open("@string/path");
// the rest is as in my first post above....
我得到的错误是:
The method onCreate(SQLiteDatabase, Context) of type DQDbAdapter.DatabaseHelper must override or implement a supertype method
请您帮我解决此错误。感谢
答案 0 :(得分:4)
您是否需要在应用中填充数据库,还是可以提前准备?见这里:
Populate Android Database From CSV file?
如果您真的想要在您发布的代码中执行您要执行的操作,则可以执行以下操作:
public class DatabaseHelper extends SQLiteOpenHelper {
...
private Context context;
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
...
context.getAssets()...
}