2012-09-13 43 views
-1

我需要在Android應用程序中使用內部SQLite數據庫使用Eclipse.i嘗試了很多方法,但我無法獲得解決方案。 在此先感謝。如何連接我的Android應用程序中的內部SQLite數據庫?

+0

可能重複[?如何將SQLite數據庫在我的Android應用程序連接(http://stackoverflow.com/questions/12400333/how-to-connect- -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

感謝你的支持,這很好,很清楚,並且會幫助我在下一個小小的Android版本中實現。 – RossC

+0

這是我的榮幸。 –

相關問題