2

I found this excellent example of a SQLiteOpenHelper class which is really nicely documented, and I think I can use it for my application; the thing is I'm still struggling to determine if the database created by my app already exists

My app has a main activity Java class [imaginatively named] 'ActivityMain' which at the moment calls the void dbTest();

public void DBTest() {

        SQLiteDatabase myDB = null;

        /* Create a Database. */
        try {
            myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);

            /* Create a Table in the Database. */
            myDB.execSQL("CREATE TABLE IF NOT EXISTS "
                    + DATABASE_TABLE
                    + " (" + KEY_ID + " integer primary key autoincrement, "
                    + KEY_SCRIPT_NAME + " text, " + KEY_SCRIPT_BODY + " text, "
                    + KEY_SU_NEEDED + " short);");

            /* Insert data to a Table*/
            myDB.execSQL("INSERT INTO "
                    + DATABASE_TABLE
                    + " (" + KEY_SCRIPT_NAME
                    + ", " + KEY_SCRIPT_BODY
                    + ", " + KEY_SU_NEEDED + ")"
                    + " VALUES ('CPU information', 'cat /proc/cpuinfo', 1);");

            /*retrieve data from database */
            Cursor c = myDB.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);

            int scriptName = c.getColumnIndex("name");

            // Check if our result was valid.
            c.moveToFirst();
            // cursor left as it came from the database because it starts at the row before the first row
            ArrayList<String> sData = new ArrayList<String>();
            if (c != null) {
                do {
                    String Name = c.getString(scriptName);
                    sData.add(Name);
                } while (c.moveToNext());
            }

            ListView lv = (ListView) findViewById(R.id.mainListView);
            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, sData));
            lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        } catch (Exception e) {
            Log.e("Error", "Error", e);
        } finally {
            if (myDB != null)
                myDB.close();
        }

In there it creates the database an inserts a line then displays it back in a ListView, currently this will just insert the same row each time the app is started so I want to check to see if the database is already there.

I want the have the db start out with some initial values on there thats why I'm inserting the data, the user can then delete it if they like

So in my 'ActivityMain' class I want to call the createDataBase(); method from the 'DatabaseHelper' class I have used from the sample linked but can't

Is it something like:

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

                try {
            createDataBase();
            catch(SQLiteException e){
                // database doesn't exist yet.
                return false;
            }

I have a boolean function in the 'ActivityMain' class which works fine but I'm not sure that this is the right way to do it and in fact should be doing all of this through the helper class

private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
        return false;
    }
    return checkDB != null ? true : false;
}

Could someone give me some pointers please?

Many thanks :)

spences10
  • 570
  • 1
  • 13
  • 32

3 Answers3

1

Tutorials are nice but nothing like official API documentation. Always read the official documentation. Tutorials, for the sake of simplicity, always omit stuff (sometimes important stuff).

As you can see, getReadableDatabse() and/or getWritableDatabase() will automatically call onCreate() if DB does not exist.

Here's and example on how I do it (not tested but should show you how to do it):

public class YourDBManager extends SQLiteOpenHelper {

    private SQLiteDatabase db = null;

    public YourDBManager(final Context context, final String dbName, final int dbVersion) {
        super(context, dbName, null, dbVersion);
        db = getWritableDatabase();
    }

    /** Initializes your DB */
    private void initializeDB(final SQLiteDatabase db) throws SQLException {
        // Do whatever you want to do to initialize your DB here
    }

    /** 
     * This method is NOT called directly by you but called by SQLiteOpenHelper, 
     * but by getReadableDatabase()/getWritableDatabase() in case it doesn't exist.
     * Here you do whatever you want to do to initialize the DB the first time it is created.
     */
    @Override
    public void onCreate(final SQLiteDatabase db) throws SQLException {
        Log.i(TAG, "=====DATABASE DOES NOT EXIST: CREATING IT======");
        initializeDB(db);
    }
}

public class YourActivity extends Activity {

    private YourDBManager dbMan = null;

    /** Do NOT call from UIThread! */
    private void initializeDBManager() {
        dbMan = new YourDBManager(this, "mydatabase", 1);
    }
}

Hope this helps.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • How do I call '`createDataBase`' from my '`MainActivity`' class? – spences10 Jan 09 '13 at 17:04
  • Please read the documentation I linked to. `createDatabase()` is called by `getReadableDatabse()` and/or `getWritableDatabase()`, **not by you**. You have to implement `createDatabase()`. – m0skit0 Jan 09 '13 at 19:01
  • I have read the documentation, there is no part detailing how to call the methods. I can't just stick in the class name with the method. I'm getting really frustrated with the lack of examples or something coherent – spences10 Jan 09 '13 at 20:10
  • Sorry, I mixed `createDatabase()` with `onCreate()`. I updated my answer with more details and an example. – m0skit0 Jan 10 '13 at 09:17
1

You can find out if the database file exists or not by using

File dbFile = context.getDatabasePath(DATABASE_NAME);
if(dbFile.exists()){
// do something
}

That won't tell you if the database is valid or anything though.

Jon F Hancock
  • 3,349
  • 3
  • 23
  • 26
1

I think you are already doing things the right way. There are a few other questions on the topic ( such as Query if Android database exists! and Android - Does SQLite Database Exist?) which recommend opening the database, and then catching the exception to show that the DB does not exist.

Community
  • 1
  • 1
HaemEternal
  • 2,229
  • 6
  • 31
  • 50