【发布时间】:2011-07-31 11:35:26
【问题描述】:
我是 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() 行上收到 Eclipse 错误:
-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
请你帮我解决这个错误。谢谢
【问题讨论】: