2011-09-16 17 views
3

我有延伸SQLiteOpenHelper,它看起來像這樣的自定義DataBaseHelper類初始化SQLite數據庫:如何一次從一個輔助類中的Android

package com.stampii.stampii.comm.rpc; 


import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.sql.ResultSet; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class DataBaseHelper extends SQLiteOpenHelper{ 

    private static SQLiteDatabase sqliteDb; 
    private static DataBaseHelper instance; 
    private static final int DATABASE_VERSION = 1; 
    // the default database path is : 
    // /data/data/pkgNameOfYourApplication/databases/ 
    private static String DB_PATH_PREFIX = "/data/data/"; 
    private static String DB_PATH_SUFFIX = "/databases/"; 
    private static final String TAG = "DataBaseHelper"; 
    private Context context; 

    /*** 
    * Contructor 
    * 
    * @param context 
    *   : app context 
    * @param name 
    *   : database name 
    * @param factory 
    *   : cursor Factory 
    * @param version 
    *   : DB version 
    */ 
    public DataBaseHelper(Context context, String name, 
        CursorFactory factory, int version) { 
      super(context, name, factory, version); 
      this.context = context; 
      Log.i(TAG, "Create or Open database : " + name); 
    } 

    /*** 
    * Initialize method 
    * 
    * @param context 
    *   : application context 
    * @param databaseName 
    *   : database name 
    */ 
    public static void initialize(Context context, String databaseName) { 
      if (instance == null) { 
        /** 
        * Try to check if there is an Original copy of DB in asset 
        * Directory 
        */ 
        if (!checkDatabase(context, databaseName)) { 
          // if not exists, I try to copy from asset dir 
          try { 
           copyDataBase(context, databaseName); 
          } catch (IOException e) { 
            Log.e(TAG,"Database "+ databaseName+" does not exists and there is no Original Version in Asset dir"); 
          } 
        } 

        Log.i(TAG, "Try to create instance of database (" + databaseName 
            + ")"); 
        instance = new DataBaseHelper(context, databaseName, 
            null, DATABASE_VERSION); 
        sqliteDb = instance.getWritableDatabase(); 
        Log.i(TAG, "instance of database (" + databaseName + ") created !"); 
      } 
    } 

    /*** 
    * Static method for getting singleton instance 
    * 
    * @param context 
    *   : application context 
    * @param databaseName 
    *   : database name 
    * @return : singleton instance 
    */ 
    public static final DataBaseHelper getInstance(
        Context context, String databaseName) { 
      initialize(context, databaseName); 
      return instance; 
    } 

    /*** 
    * Method to get database instance 
    * 
    * @return database instance 
    */ 
    public SQLiteDatabase getDatabase() { 
      return sqliteDb; 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
      Log.d(TAG, "onCreate : nothing to do"); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      Log.d(TAG, "onUpgrade : nothing to do"); 

    } 

    /*** 
    * Method for Copy the database from asset directory to application's data 
    * directory 
    * 
    * @param databaseName 
    *   : database name 
    * @throws IOException 
    *    : exception if file does not exists 
    */ 
    public void copyDataBase(String databaseName) throws IOException { 
      copyDataBase(context, databaseName); 
    } 

    /*** 
    * Static method for copy the database from asset directory to application's 
    * data directory 
    * 
    * @param aContext 
    *   : application context 
    * @param databaseName 
    *   : database name 
    * @throws IOException 
    *    : exception if file does not exists 
    */ 
    private static void copyDataBase(Context aContext, String databaseName) 
        throws IOException { 

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

      // Path to the just created empty db 
      String outFileName = getDatabasePath(aContext, databaseName); 

      Log.i(TAG, "Check if create dir : " + DB_PATH_PREFIX 
          + aContext.getPackageName() + DB_PATH_SUFFIX); 

      // if the path doesn't exist first, create it 
      File f = new File(DB_PATH_PREFIX + aContext.getPackageName() 
          + DB_PATH_SUFFIX); 
      if (!f.exists()) 
        f.mkdir(); 

      Log.i(TAG, "Trying to copy local DB to : " + outFileName); 

      // 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(); 

      Log.i(TAG, "DB (" + databaseName + ") copied!"); 
    } 

    /*** 
    * Method to check if database exists in application's data directory 
    * 
    * @param databaseName 
    *   : database name 
    * @return : boolean (true if exists) 
    */ 
    public boolean checkDatabase(String databaseName) { 
      return checkDatabase(context, databaseName); 
    } 

    /*** 
    * Static Method to check if database exists in application's data directory 
    * 
    * @param aContext 
    *   : application context 
    * @param databaseName 
    *   : database name 
    * @return : boolean (true if exists) 
    */ 
    private static boolean checkDatabase(Context aContext, String databaseName) { 
      SQLiteDatabase checkDB = null; 

      try { 
        String myPath = getDatabasePath(aContext, databaseName); 

        Log.i(TAG, "Trying to conntect to : " + myPath); 
        checkDB = SQLiteDatabase.openDatabase(myPath, null, 
            SQLiteDatabase.OPEN_READONLY); 
        Log.i(TAG, "Database " + databaseName + " found!"); 
        checkDB.close(); 
      } catch (SQLiteException e) { 
        Log.i(TAG, "Database " + databaseName + " does not exists!"); 

      } 

      return checkDB != null ? true : false; 
    } 

    /*** 
    * Method that returns database path in the application's data directory 
    * 
    * @param databaseName 
    *   : database name 
    * @return : complete path 
    */ 
    private String getDatabasePath(final String databaseName) { 
      return getDatabasePath(context, databaseName); 
    } 

    /*** 
    * Static Method that returns database path in the application's data 
    * directory 
    * 
    * @param aContext 
    *   : application context 
    * @param databaseName 
    *   : database name 
    * @return : complete path 
    */ 
    private static String getDatabasePath(Context aContext, String databaseName) { 
      return DB_PATH_PREFIX + aContext.getPackageName() + DB_PATH_SUFFIX 
          + databaseName; 
    } 

    public boolean executeQuery(String tableName,String keys,String value){ 
     return execQuery(tableName,keys,value); 
    } 

    private static boolean execQuery(String tableName,String key,String value){ 
     sqliteDb = instance.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 
     values.put(key, value); 
     sqliteDb.insert(tableName, null, values); 

     return true; 

    } 

    public boolean updateSQL(String tableName,String key,String value){ 
     return updateData(tableName,key,value); 
    } 

    private static boolean updateData(String tableName,String key,String value){ 
     sqliteDb = instance.getWritableDatabase(); 
     String where = "code_id=?"; 
     ContentValues values = new ContentValues(); 
     values.put(key, value); 
     values.put(key, value); 
     sqliteDb.update(tableName, values, where, new String[] {"3"}); 
     return true; 
    } 

    public boolean deleteSQL(String tableName){ 
     return deleteData(tableName); 
    } 

    private static boolean deleteData(String tableName){ 
     sqliteDb = instance.getWritableDatabase(); 
     String where = "code_id=?"; 
     sqliteDb.delete(tableName, where, new String[] {"5"}); 
     return true; 
    } 

    public Cursor executeSQLQuery(String query){ 
     return sqliteDb.rawQuery(query,null); 
    } 

} 

我的問題是:我怎麼能初始化數據庫只有一次,可以從我的所有活動中訪問它? (提示:我在我的資產文件夾,我複製到當應用程序星星我的系統數據庫文件夾sqlite的文件)

提前感謝!

編輯:我忘了說,我在我的應用2個不同的SQLite數據庫,我希望能夠來初始化他們的整個應用程序,並可以使用了進來就是我試圖做一些事情:

DataBaseHelper dbHelper; 
//some code 
dbHelper = new DataBaseHelper(context, "ops_sys_tpl.sqlite", null, 1); 
     DataBaseHelper.initialize(context, "stampii_sys_tpl.sqlite"); 

     dbHelper.copyDataBase("ops_sys_tpl.sqlite"); 

     dbHelper.getDatabase(); 
     dbHelper.executeQuery("users", "objectId", "2"); 
     dbHelper.executeQuery("users","serverName","stampii"); 
     dbHelper.executeQuery("users", "objectId", "3"); 
     dbHelper.executeQuery("users","serverName","stampii"); 
     dbHelper.executeQuery("users", "objectId", "3"); 

回答

4

創建您的實例只有一次這樣的,同樣的代碼,你可以在DB處理類中添加,但我寧願保持獨立。

public class MyTestDatabaseInstanceHolder { 

    public MyTestDBHandler DBHelper; 
    public static SQLiteDatabase m_ObjDataBase; // This is global variable to access across the applicaiton 

    public static void createDBInstance(Context pContext){ 
     if(DBHelper == null) { 
      DBHelper = new WLDBHandler(pContext); // This will be your DB Handler Class 
      m_cObjDataBase = DBHelper.openAndCreateDataBase(); // Initialze the DB Note: openAndCreateDataBase is a utility method created by you to do everything an return the DB object 
     } 
     } 
} 

在您的入口點(閃屏)稱此:

MyTestDatabaseInstanceHolder.createDBInstance(getApplicationContext()); 

用法 - 一些其他類:

MyTestDatabaseInstanceHolder.m_ObjDataBase.rawQuery(---); 
+0

其實我沒有得到,如果MyTestDBHandler在你的代碼是幫助我的班? –

+0

是ofcourse ... –

+0

好吧,我只是想成爲sure.Thanks了很多,我會努力的! –

1

我想初始化你的數據庫,你必須通過活動的背景下,您正在使用它,所以在每一個活動中使用它,你必須在每一個活動來初始化。如果我錯了,請讓我知道。

+0

實際上那是我做的方式now.But當我必須從助手類初始化數據庫時,我該如何繼續? –

+0

則只是通過活動引用該助手類,並用它來初始化數據庫。 – user370305

+0

但按照hotveryspicy建議這是個壞主意,保持datbase狀態如創建,打開關閉你必須使用活動的方法,如的onCreate()的onStop()的onDestroy()這就是爲什麼我suggeste您在活動初始​​化數據庫。謝謝。 :-) – user370305

相關問題