Search code examples
androidsqlitefeed

What is the best way to structure my android Sqlite flow?


I am doing some refactoring of my app and am trying to use best practice for handling DB. Can someone advise the best way to handle checking if the database exists and performing updates. The method I am currently using is: 1. Open readable Database. 2. Doing a check if the table is in there, if not firing a Sql exception 3a In the exception handling I am closing the database 3b. Opening a writeable database: 3c Performing a create table in the sql exception and performing an initial update from my Json feed.

Is this is best way to manage the database and update or should I be doing it differently to be more efficient?


Solution

  • I am using the following method:

      private boolean checkDataBase(){
    
        SQLiteDatabase checkDB = null;
    
        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
            long result =  DatabaseUtils.longForQuery(checkDB,"SELECT count() FROM sqlite_master WHERE type='table' AND name='table_name'",null);
            if(result == 0)
                checkDB = null;
    
        }catch(SQLiteException e){
    
            Log.e("", e.getLocalizedMessage()+e.getMessage()+e.getCause()+
                    Arrays.toString(e.getStackTrace()));
    
        }
    
        if(checkDB != null){
    
            checkDB.close();
    
        }
     return checkDB != null ? true : false;
    }