はステップ
により溶液の段階である私は、インサートのクエリが含まれている.sql
ファイルを作成します(一部は複数行のクエリを含める)で終わります:。
私のonCreate()
の方法では、SQLiteOpenHelper
の方法では、getFileLineCount()
を使用して私のファイルの行をカウントしています。このメソッドは、私にラインのカウントを返します。この行数は決して使用されませんが、すべての照会が1行であれば、それは有効になるかもしれないからです。この方法はスキップできます。
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE \"" + TABLE_POEM + "\" (\"" + POEM_LOCAL_ID + "\" INTEGER PRIMARY KEY AUTOINCREMENT , \"" + POEM_TEXT + "\" TEXT,\"" + POEM_ID + "\" INTEGER , \"" + POEM_IS_FAV + "\" TEXT);");
int totalLineCount = getFileLineCount("poem.sql");
int insertCount = insertFromFile(db, "poem.sql", totalLineCount);
Log.d("DatabaseHelper", "------------onCreate(SQLiteDatabase db) >>>>>>> completed--------");
}
private int getFileLineCount(String assetFilePath) {
InputStream insertStream = null;
int totalCount = 0;
try {
insertStream = context.getAssets().open(assetFilePath);
totalCount = FileUtil.countLines(new BufferedInputStream(insertStream));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (insertStream != null) {
try {
insertStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return totalCount;
}
この方法を使用すると、ファイルからクエリを挿入します。これは、シングルラインクエリとマルチラインクエリの両方を処理します。まず、行に";"
が含まれているかどうかをチェックします。かなりシンプルだったのは最後でした。
while ((currentLine = insertReader.readLine()) != null) {
if (currentLine.length() != 0) {
if (currentLine.charAt(currentLine.length() - 1) == ';') {
insertInDb(db, insertStr + "\n" + currentLine);
insertStr = "";
} else {
insertStr += currentLine;
}
}
}
private int insertFromFile(SQLiteDatabase db, String assetFilePath, int totalCount) {
int result = 0;
BufferedReader insertReader = null;
try {
InputStream insertStream = context.getAssets().open(assetFilePath);
insertReader = new BufferedReader(new InputStreamReader(insertStream));
db.beginTransaction();
while (insertReader.ready()) {
// String insertStr = insertReader.toString();
String insertStr = "";
String currentLine;
while ((currentLine = insertReader.readLine()) != null) {
if (currentLine.length() != 0) {
if (currentLine.charAt(currentLine.length() - 1) == ';') {
insertInDb(db, insertStr + "\n" + currentLine);
insertStr = "";
} else {
insertStr += currentLine;
}
}
}
}
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (insertReader != null) {
try {
insertReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
db.endTransaction();
}
return result;
}
private void insertInDb(SQLiteDatabase db, String assetFilePath) throws IOException {
if (assetFilePath != null && assetFilePath.length() > 0) {
SQLiteStatement statement = db.compileStatement(assetFilePath);
statement.execute();
}
}
このテクニックを使用して4000個のレコードをdbに挿入しました。そして、それは遅れのほとんどなくうまくいきました。誰かがそれのためのバッターの解決策を持っている場合。親切に投稿してください。
誰でも?助けて??? –
あなたは[アプリケーションと共にDBを発送する]だけではどうですか(http://stackoverflow.com/questions/513084/how-to-ship-an-android-application-with-a-database)? –