0
我設計了一個數據庫與SQL精簡版專家的專業,並將其複製到文件夾的資產,但我不能把它複製到數據庫文件夾如何將數據庫從資產文件夾複製到數據庫文件夾?
我不想用我的代碼,因爲它不工作...
任何人都可以分享他的代碼嗎?
對不起我的英語這麼差
我設計了一個數據庫與SQL精簡版專家的專業,並將其複製到文件夾的資產,但我不能把它複製到數據庫文件夾如何將數據庫從資產文件夾複製到數據庫文件夾?
我不想用我的代碼,因爲它不工作...
任何人都可以分享他的代碼嗎?
對不起我的英語這麼差
我的問題解決了:)
大家,有從資源文件夾到數據庫文件夾複製數據庫的問題,可以使用下面的代碼
package com.example.zedaastan;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class database extends SQLiteOpenHelper {
private static SQLiteDatabase mydb;
private static final int DATABASE_VERSION = 1;
private static final String DB_NAME = "database";
private static final String DB_PATH = "/databases/";
static Context ctx;
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public database(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
ctx = context;
}
public void CopyDataBaseFromAsset() throws IOException{
InputStream myInput = ctx.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = getDatabasePath();
// if the path doesn't exist first, create it
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH);
if (!f.exists())
f.mkdir();
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void open(){
File dbFile = ctx.getDatabasePath(DB_NAME);
}
public void close(){
mydb.close();
}
private static String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH
+ DB_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException{
File dbFile = ctx.getDatabasePath(DB_NAME);
if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS |
SQLiteDatabase.CREATE_IF_NECESSARY);
}
顯示您的代碼。 – Downvoter