2014-12-15 3 views
-1

SQLiteManager를 사용하여 여러 테이블이있는 .sqlite 파일을 만들었습니다. Google Play 스토어에 게시 된 프로젝트의 에셋 폴더에 .sqlite 파일을 저장하려고합니다.자산 폴더에서 sqlite 데이터베이스를 어떻게 업데이 트합니까?

하지만 이제는 테이블에 몇 가지 변경 사항을 추가했습니다. 기존 테이블에 테이블과 수정 된 열이 추가되었습니다.

기존 사용자는 어떻게 업데이트 된 데이터베이스를 얻습니까? SQLiteOpenHelper 클래스의 onUpgrade 메서드는 내 데이터베이스를 업그레이드하는 데 도움이됩니까?

+0

봅니다 –

+0

는 미리 만들어진 데이터베이스와'SQLiteOpenHelper'를 사용하지 마십시오 응답합니다. 대신에'SQLiteAssetHelper'를 사용하십시오. https://github.com/jgilfelt/android-sqlite-asset-helper – laalto

답변

2

당신은, 데이터베이스 파일에 업그레이드/변경에이

같은 것을 사용하는 DATABASE_VERSION 값을 변경할 수 있습니다. 제 questions.It은 "보기"및 따라서 좋은 품질을 줄일 피하기 위해

public class Cls_DatabaseHelper extends SQLiteOpenHelper { 

    private static String DB_PATH = ""; 

    private static final int DATABASE_VERSION = 1; 

    private static String DB_NAME = "mydatabase.db"; 

    public static SQLiteDatabase myDataBase; 
    private static Cls_DatabaseHelper myDBHelper = null; 

    private final Context myContext; 



    /** 
    * Constructor Takes and keeps a reference of the passed context in order to 
    * access to the application assets and resources. 
    * 
    * @param context 
    */ 
    private Cls_DatabaseHelper(Context context) { 

     super(context, DB_NAME, null, 1); 
     this.myContext = context; 
     DB_PATH = myContext.getDatabasePath(DB_NAME).getPath(); 
     try { 
      openDataBase(); 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public static Cls_DatabaseHelper getInstance(Context context) { 
     if (myDBHelper == null) { 
      myDBHelper = new Cls_DatabaseHelper(context.getApplicationContext()); 
     } 

     return myDBHelper; 
    } 

    /** 
    * Creates a empty database on the system and rewrites it with your own 
    * database. 
    * */ 
    public void createDataBase() throws IOException { 

     boolean dbExist = checkDataBase(); 

     if (dbExist) { 
      // do nothing - database already exist 
     } else { 

      // By calling this method and empty database will be created into 
      // the default system path 
      // of your application so we are gonna be able to overwrite that 
      // database with our database. 
      this.getReadableDatabase(); 

      try { 

       copyDataBase(); 

      } catch (IOException e) { 

       throw new Error("Error copying database"); 

      } 
     } 

    } 

    /** 
    * Check if the database already exist to avoid re-copying the file each 
    * time you open the application. 
    * 
    * @return true if it exists, false if it doesn't 
    */ 
    private boolean checkDataBase() { 

     SQLiteDatabase checkDB = null; 

     try { 
      String myPath = DB_PATH; 
      checkDB = SQLiteDatabase.openDatabase(myPath, null, 
        SQLiteDatabase.OPEN_READONLY 
          | SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
      int DB_EXIST_VERSION = PreferenceManager 
        .getDefaultSharedPreferences(myContext).getInt(
          "DB_VERSION", 0); 
      if (DATABASE_VERSION != DB_EXIST_VERSION) { 
       checkDB = null; 
      } 

     } catch (SQLiteException e) { 

      // database does't exist yet. 

     } 

     if (checkDB != null) { 

      checkDB.close(); 

     } 

     return checkDB != null ? true : false; 
    } 

    /** 
    * Copies your database from your local assets-folder to the just created 
    * empty database in the system folder, from where it can be accessed and 
    * handled. This is done by transfering bytestream. 
    * */ 
    private void copyDataBase() throws IOException { 

     // Open your local db as the input stream 
     InputStream myInput = myContext.getAssets().open(DB_NAME); 

     // Path to the just created empty db 
     String outFileName = DB_PATH; 

     // 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(); 
     PreferenceManager.getDefaultSharedPreferences(myContext).edit() 
       .putInt("DB_VERSION", DATABASE_VERSION).commit(); 
    } 

    public void openDataBase() throws SQLException, IOException { 
     createDataBase(); 
     // Open the database 
     String myPath = DB_PATH; 
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READWRITE 
         | SQLiteDatabase.NO_LOCALIZED_COLLATORS); 

    } 

    @Override 
    public synchronized void close() { 

     if (myDataBase != null) 
      myDataBase.close(); 
     myDataBase = null; 
     myDBHelper = null; 

     super.close(); 

    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

    } 

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

    } 

    /********************************************* 
    * Method to execute a SQL statemtn and return a custom adapter. Use only to 
    * search Station Codes 
    *********************************************/ 
    public Cursor executeSQLStatement(String SQLStatement) { 

     Cursor c = null; 
     try { 
      if (myDataBase != null) { 
       c = myDataBase.rawQuery(SQLStatement, new String[] {}); 
       if (c != null) 
        c.moveToFirst(); 

      } 
     } 

     catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return c; 
    } 
    } 
+0

답장을 보내 주셔서 감사합니다. 이제 데이터베이스를 복사 할 때 자산 폴더에서 db의 빈 복사본을 만들 때 기존 db 테이블 레코드를 최신 db로 복사하는 방법은 무엇입니까? 내부 저장소로? –

+0

코드를 통해? 왜 그렇게해야하지? assets 폴더에서 mydatabase.db (또는 db 파일의 이름이 무엇이든)를 바꾸고 DATABASE_VERSION 값을 변경하면됩니다. 데이터베이스 파일에서 작업을 수행하려면 원하는 도구 인 SQLLITE Browser 내 대답이 원하는 경우 pls는 내 대답을 받아들입니다 .-) –

+0

하지만 이전 DB의 유용한 레코드가 필요합니다. 번역. 그래서 최신 db에 복사해야합니다. –

관련 문제