1

Based on http://developer.android.com/guide/topics/data/data-storage.html#db it seems like I'd need another Java Class file (which I made), but now I've run into a rather sad problem: I'm not sure how to handle it.

How would I call it in my main activity and would it only create the database once, or would it try to re-create the database every time it runs?

Rhyono
  • 2,420
  • 1
  • 25
  • 41
  • The answer from Rakshi may be quite short but it is absolutely correct. The `SQLiteOpenHelper` (and any class you create which extends it) will check first to see if the DB exists. If it doesn't exist then it will be created. After that, as long as the database 'version' is the same, it will continue to simply use the database that was initially created. If you supply a different (higher) database version number then `onUpgrade` will be called allowing dynamically updating the DB (creating / dropping tables, adding new fields to tables and so on). – Squonk Mar 01 '12 at 06:54

3 Answers3

4

This would 'create' the database only for the first time. After that you can use an object of that SQLiteOpenHelper class to access that database. Note that you don't have to worry about the recreation of the database, android will take care of that if you use the SQLiteOpenHelper approach.

Taking the data-storage example forward you would create an object of that and then use the getWriteableDatabase method on that to get write access to the database

DictionaryOpenHelper myDictionary;
myDictionary = new DictionaryOpenHelper(this);
SQLiteDatabase db = myDictionary.getWritableDatabase();

//to enter values in the db
ContentValues values = new ContentValues();
values.put("name","Rhyno");
db.insert(nameOfTable, null, values);

For a more detailed example please refer to this tutorial: http://marakana.com/forums/android/examples/55.html

Soham
  • 4,940
  • 3
  • 31
  • 48
2

it creates only if it dosent exists.

Rakshi
  • 6,796
  • 3
  • 25
  • 46
0

An SQLiteOpenHelper has 2 very useful methods: onCreate() and onUpgrade().

  1. onCreate() will only be called if the database does not exist.
  2. onUpgrade() will only be called if the DATABASE_VERSION (passed into the constructor when you create the SQLiteOpenHelper instance) increases.

There is also onDowngrade() and onOpen() when the DATABASE_VERSION decreases or the database is opened, respectively.

onCreate() is where you want to do your db.execSQL("CREATE TABLE ....") to first make your tables.

You can then use your SQLiteOpenHandler's instance to do dbHandler.getWritableDatabase() and dbHandler.getReadableDatabase() which return a readable or writable SQLiteDatabase object in your code. You can then writableDb.insert() or readableDB.query() to put and get stuff from your db.

CompEng88
  • 1,336
  • 14
  • 25