2012-12-17 3 views
1
공식 안드로이드 개발자 웹 사이트 먼저 우리는이 같은 인 첫 번째 '스키마와 계약을 정의'해야한다는 언급

:안드로이드에서 데이터베이스를 설정

public static abstract class FeedEntry implements BaseColumns { 
public static final String TABLE_NAME = "entry"; 
public static final String COLUMN_NAME_ENTRY_ID = "entryid"; 
public static final String COLUMN_NAME_TITLE = "title"; 
public static final String COLUMN_NAME_SUBTITLE = "subtitle"; 
... 

}

두 번째 단계 언급 된 'SQL 도우미를 사용하여 데이터베이스 만들기'입니다.

그러나 웹에서 본 모든 자습서는 '도우미'를 사용하여 직접 클래스를 만듭니다. example. 올바른 방법은 무엇입니까? 양자 모두?

또한 주 활동에 데이터베이스를 정의하고 만들거나 데이터베이스에 대해 별도의 활동을 만들어야합니까?

답변

2

SQLite 브라우저 (예 : SQLite Maestro)에서 데이터베이스를 생성하고 프로젝트의 자산 폴더에 데이터베이스를 복사하십시오. MainActivity에서 createDatabase() 메소드를 호출하십시오 (이는 앱의 런처 활동의 첫 번째 항목입니다).

private void createDataBase(){ 
    DataBaseHelper db = new DataBaseHelper(this); 
    try { 
     db.createDataBase(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }finally{ 
     db.close(); 
    } 
} 

그리고 헬퍼 클래스 :

public class DataBaseHelper extends SQLiteOpenHelper{ 

    private static String DB_PATH = "/data/data/your.package/databases/"; 
    private static String DB_NAME = "YourDataBaseName.sqlite"; 
    private static int DB_VERSION = 1; 

    private static short WRITE_BUFFER_SIZE = 8192; 

    private Context context; 

    /** 
    * Constructor 
    * Takes and keeps a reference of the passed context in order to access to the application assets and resources. 
    * @param context Current application context 
    */ 
    public DataBaseHelper(Context context) { 
     super(context, DB_NAME, null, DB_VERSION); 

     this.context = context; 
    } 

    /** 
    * Creates a empty database on the system and rewrites it with your own database. 
    * */ 
    public synchronized 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.getWritableDatabase(); 

      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 + DB_NAME; 

      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
     }catch(SQLException e){ 
      e.printStackTrace(); 
      //database does't exist yet. 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 

     if(checkDB != null){ 
      if(checkDB.getVersion() < DB_VERSION){ 
       checkDB.close(); 
       return false; 
      }else{ 
       checkDB.close(); 
       return true; 
      } 
     } 

     return 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 = context.getAssets().open(DB_NAME); 

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

     //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[WRITE_BUFFER_SIZE]; 
     int length; 
     while ((length = myInput.read(buffer)) > 0){ 
      myOutput.write(buffer, 0, length); 
     } 
     //Close the streams 
     myOutput.flush(); 
     myOutput.close(); 
     myInput.close(); 
     this.getWritableDatabase().close(); 
    } 

    @Override 
    public synchronized void close() { 
      super.close(); 
    } 

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

    @Override 
    public void onCreate(SQLiteDatabase db) { 
    } 

    /** 
    * Delete database and create new one or copy from assets if exists. 
    */ 
    public void clearDatabase(){  
     context.deleteDatabase(DB_NAME); 
     try { 
      createDataBase(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     this.getWritableDatabase().close(); 
    } 
} 
+0

이 헬퍼 클래스가 너무 'MainActivity'아래에 위치해야 하는가? –

+0

"Under"는 무엇을 의미합니까? Helper 클래스는 프로젝트의 어느 위치 에나 배치 할 수 있습니다. 예 : com.projectname.Activity 패키지의 MainActivity, com.projectname.DATABASE 패키지의 DataBaseHelper –

+0

좋습니다! 고맙습니다. –

관련 문제