2015-12-28 3 views
-1

У меня есть одно приложение для Android, которое имеет базу данных sqllite, расположенную в папке с ресурсами. Я опубликовал приложение в playstore с версией базы данных = null, чем версия базы данных = 1, версия базы данных = 2 и теперь хочу опубликовать приложение с версией базы данных = 3. У меня есть условие для удаления последних данных и копирования новых данных при обновлении. его работа, если у пользователя есть приложение, установленное с версией 2, если у пользователя есть база данных версии 1, чем его, к сожалению, остановлена ​​на основной деятельности. Что является проблемой в моем состоянии для базы данных копий? Мой класс помощника базы данных выглядит следующим образом. БлагодаряSQLlite DataBase on Upgrade Application

public class DataBaseHandler extends SQLiteOpenHelper { 
 

 
\t private static String DB_PATH; 
 
\t private static String DB_NAME = "SuccessQuotesNew"; 
 
\t private SQLiteDatabase myDataBase; 
 
\t private static int DATABASE_VERSION = 1; 
 
\t private final Context myContext; 
 
\t public DataBaseHandler(Context context) { 
 

 
\t \t super(context, DB_NAME, null, DATABASE_VERSION); 
 
\t \t this.myContext = context; 
 
\t \t DB_PATH = context.getDatabasePath(DB_NAME).toString(); 
 
\t \t Log.e("path", DB_PATH); 
 
\t } 
 

 
\t public void createDataBase() throws IOException { 
 

 
\t \t boolean dbExist = checkDataBase(); 
 
\t \t if(dbExist) 
 
\t \t { 
 
\t \t if(DATABASE_VERSION == 2) 
 
\t \t { 
 
\t \t \t 
 

 
\t \t \t try { 
 

 
\t \t \t \t copyDataBase(); 
 
\t \t \t \t DATABASE_VERSION = 3; 
 

 
\t \t \t } catch (IOException e) { 
 

 
\t \t \t \t throw new Error("Error copying database"); 
 

 
\t \t \t } 
 
\t \t \t 
 
\t \t }else 
 
\t \t { 
 
\t \t SQLiteDatabase database = null; 
 
\t \t database = this.getWritableDatabase(); 
 
\t \t String query_count = "SELECT version FROM users"; 
 
\t \t \t \t 
 
\t \t Cursor c_count = database.rawQuery(query_count, null); 
 
\t \t 
 
\t \t 
 
\t \t c_count.moveToFirst(); 
 
\t \t Integer count = c_count.getInt(c_count.getColumnIndex("version")); 
 
\t if(count == DATABASE_VERSION) 
 
\t { 
 
\t \t 
 
\t }else 
 
\t { 
 
\t \t this.getReadableDatabase(); 
 

 
\t \t try { 
 

 
\t \t \t copyDataBase(); 
 

 
\t \t } catch (IOException e) { 
 

 
\t \t \t throw new Error("Error copying database"); 
 

 
\t \t } 
 
\t } 
 

 
\t } 
 
\t \t }else 
 
\t \t { 
 
\t \t \t this.getReadableDatabase(); 
 

 
\t \t \t try { 
 

 
\t \t \t \t copyDataBase(); 
 
\t \t \t \t DATABASE_VERSION = 2; 
 

 
\t \t \t } catch (IOException e) { 
 

 
\t \t \t \t throw new Error("Error copying database"); 
 

 
\t \t \t } 
 

 
\t \t } 
 
\t \t \t 
 
\t } 
 

 
\t private boolean checkDataBase() { 
 

 
\t \t SQLiteDatabase checkDB = null; 
 

 
\t \t try { 
 
\t \t \t String myPath = DB_PATH; 
 
\t \t \t checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 
 

 
\t \t } catch (SQLiteException e) { 
 

 
\t \t \t // database does't exist yet. 
 

 
\t \t } 
 

 
\t \t if (checkDB != null) { 
 

 
\t \t \t checkDB.close(); 
 

 
\t \t } 
 

 
\t \t return checkDB != null ? true : false; 
 
\t } 
 

 
\t private void copyDataBase() throws IOException { 
 

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

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

 
\t \t // Open the empty db as the output stream 
 
\t \t OutputStream myOutput = new FileOutputStream(outFileName); 
 

 
\t \t // transfer bytes from the inputfile to the outputfile 
 
\t \t byte[] buffer = new byte[1024]; 
 
\t \t int length; 
 
\t \t while ((length = myInput.read(buffer)) > 0) { 
 
\t \t \t myOutput.write(buffer, 0, length); 
 
\t \t } 
 

 
\t \t // Close the streams 
 
\t \t myOutput.flush(); 
 
\t \t myOutput.close(); 
 
\t \t myInput.close(); 
 

 
\t } 
 

 
\t // ============================================================================== 
 

 
\t public void openDataBase() throws SQLException { 
 

 
\t \t // Open the database 
 
\t \t String myPath = DB_PATH; 
 
\t \t myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 
 

 
\t } 
 

 
\t // ============================================================================== 
 

 
\t @Override 
 
\t public synchronized void close() { 
 

 
\t \t if (myDataBase != null) 
 
\t \t \t myDataBase.close(); 
 

 
\t \t super.close(); 
 

 
\t } 
 

 
\t // ============================================================================== 
 

 
\t @Override 
 
\t public void onCreate(SQLiteDatabase db) { 
 

 
\t } 
 

 
\t // ============================================================================== 
 

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

 
\t } 
 

 
}

ответ

0

Сначала у проверить версию пользователя базы данных под управлением после этого обновления базы данных

if(DATABASE_VERSION == 1) 
    { 


     try { 

      copyDataBaseForVersion1(); 
      DATABASE_VERSION = 3; 

     } catch (IOException e) { 

      throw new Error("Error copying database"); 

     } 

    } 
else if(DATABASE_VERSION == 2) 
    { 


     try { 

      copyDataBaseForVersion2(); 
      DATABASE_VERSION = 3; 

     } catch (IOException e) { 

      throw new Error("Error copying database"); 

     } 

    } 
+0

и что должно быть, если версия базы данных 2? –

+0

Спасибо, босс. Извините, я мало начинаю и так сталкиваюсь с проблемами. Его рабочий штраф без каких-либо проблем :) –

+0

@RajubhaiRathod Проверьте мой ответ –

0

Я думаю, что лучше было бы:

Вы может использовать что-то вроде этого

При обновлении/изменении в файле базы данных измените значение DATABASE_VERSION.

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; 
    } 
    }