2012-09-13 4 views
-1

내 Android 응용 프로그램에서 내부 SQLite 데이터베이스를 사용해야합니다. Eclipse.i를 사용하여 여러 가지 방법을 시도했지만 해결책을 얻지 못했습니다. 미리 감사드립니다.안드로이드 애플리케이션에서 내부 SQLite 데이터베이스를 연결하는 방법은 무엇입니까?

+0

가능한 중복 [? 내 안드로이드 응용 프로그램에서 SQLite 데이터베이스를 연결하는 방법 (http://stackoverflow.com/questions/12400333/how-to-connect- the-sqlite-database-in-my-android-application) –

답변

1

이이 솔루션을 시도 :

private static String DB_PATH = "/data/data/your.package/databases/"; 
    private static String DB_NAME = "namedatabase.sqlite"; 
    private SQLiteDatabase db; 
    private final Context context; 

    public DataBaseWorker(Context ctx) { 
     super(ctx, DB_NAME, null, 1); 
     context = ctx; 
    } 

    public void createDataBase() throws IOException { 
     boolean dbExist = checkDataBase(); 
     if (!dbExist) { 
      File wallpaperDirectory = new File(
        "/data/data/your.package/databases/"); 
      wallpaperDirectory.mkdirs(); 
      try { 
       copyDataBase(); 
      } catch (Exception e) { 
       Log.v("CREATEDATABASE", "not copy DB"); 
      } finally { 
       this.close(); 
      } 
     } 
    } 

    public boolean checkDataBase() { 
     SQLiteDatabase checkDB = null; 
     try { 
      String Path = DB_PATH + DB_NAME; 

      checkDB = SQLiteDatabase.openDatabase(Path, null, 
        SQLiteDatabase.OPEN_READONLY); 

     } catch (SQLiteException e) { 
      Log.v("CHECKDB", "not check DB"); 
     } 

     if (checkDB != null) 
      checkDB.close(); 

     return checkDB != null ? true : false; 
    } 

    private void copyDataBase() throws IOException { 
     InputStream input = context.getAssets().open(DB_NAME); 
     String outFileName = DB_PATH + DB_NAME; 
     OutputStream output = new FileOutputStream(outFileName); 

     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = input.read(buffer)) > 0) { 
      output.write(buffer, 0, length); 
     } 
     input.close(); 
     output.close(); 
    } 

    public void openDataBase() throws SQLException { 
     String Path = DB_PATH + DB_NAME;   
     db = SQLiteDatabase.openDatabase(Path, null, 
       SQLiteDatabase.OPEN_READWRITE); 
    } 

    public void close() { 
     if (db != null) 
      db.close(); 
     super.close(); 
    } 

    public void exec(String query) { 
     db.execSQL(query); 
     db.close(); 
    } 
+0

고마워, 그게 좋고 명확하고 안드로이드에 내 작은 forray에 나를 도울 것입니다. – RossC

+0

그것은 나의 기쁨이다. –

관련 문제