테스트 사이트 - 개발 중인 베타 버전입니다

[안드로이드] assets 폴더안에 db 파일 자신 앱에 복사하기

· 12년 전 · 7884
이거 고대로 사용하시면 됩니다. main oncreate 에서 저 클래스 한번만 불러와서 쓰시면 알아서 복사가 됩니다.

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

 

static String NAME = "testdb.sqlite";

static CursorFactory FACTORY = null;

static String PACKEGE = "com.example.isbnapp";

static String DB = "isbn.db";

static int VERSION  = 1;

public MySQLiteOpenHelper(Context context) {

super(context, NAME, FACTORY, VERSION);

// TODO Auto-generated constructor stub

try {

boolean bResult = isCheckDB(context);  // DB가 있는지?

Log.i("MiniApp", "DB Check="+bResult);

if(!bResult){   // DB가 없으면 복사

copyDB(context);

}else{

 

}

} catch (Exception e) {

 

}

}

// DB가 있나 체크하기

public boolean isCheckDB(Context mContext){

String filePath = "/data/data/" + PACKEGE + "/databases/" + DB;

File file = new File(filePath);

 

if (file.exists()) {

return true;

}

 

return false;

 

}

// DB를 복사하기

// assets의 /db/xxxx.db 파일을 설치된 프로그램의 내부 DB공간으로 복사하기

public void copyDB(Context mContext){

Log.d("MiniApp", "copyDB");

AssetManager manager = mContext.getAssets();

String folderPath = "/data/data/" + PACKEGE + "/databases";

String filePath = "/data/data/" + PACKEGE + "/databases/" +DB;

File folder = new File(folderPath);

File file = new File(filePath);

 

FileOutputStream fos = null;

BufferedOutputStream bos = null;

try {

InputStream is = manager.open("db/" + DB);

BufferedInputStream bis = new BufferedInputStream(is);

 

if (folder.exists()) {

}else{

folder.mkdirs();

}

 

 

if (file.exists()) {

file.delete();

file.createNewFile();

}

 

fos = new FileOutputStream(file);

bos = new BufferedOutputStream(fos);

int read = -1;

byte[] buffer = new byte[1024];

while ((read = bis.read(buffer, 0, 1024)) != -1) {

bos.write(buffer, 0, read);

}

 

bos.flush();

 

bos.close();

fos.close();

bis.close();

is.close();

 

} catch (IOException e) {

Log.e("ErrorMessage : ", e.getMessage());

} 

}

/** Called when the activity is first created. */

@Override

public void onCreate(SQLiteDatabase db) {

// String QUERY = "CREATE TABLE word (_id INTEGER PRIMARY KEY autoincrement, word_e TEXT , word_k TEXT)";

// db.execSQL(QUERY);

Log.e("ehsk", "eee");

 

//        String QUERY1 = "INSERT INTO word (word_e, word_k ) VALUES(apple , 사과)";

//        db.execSQL(QUERY1);

}

 

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

String QUERY = "DROP TABLE IF EXISTS word";

db.execSQL(QUERY);

onCreate(db);

 

 

}

}

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
384
12508
383
381
20395
12507
12506
12505
12504
12503
12502
12500
12499
12498
20392
12497
12496
12495
12494
12493
12492
12491
12490
12489
12488