JavaNullPointer
JavaNullPointer

Reputation: 1211

Filling SQLite Database with Data Once

In my application I use a SQLite DBhelper class (extend extends SqliteOpenHelper), which overwrites my onCreate, OnUpgrade-methods. Also I need to create a DBManager-class to assure a controlled access to my DB from other classes....

Now I want to set up my data for the DB. This data has to be created once at the first start of my app. How can I assure that the data is only created once from DBManager? I want to call my methods for setup DB-Data from DBManager-class to have clean software design....

Here is a code-example from DBManager:

public class DBManager {
    private static final String TAG = DBManager.class.getSimpleName();

    private DatabaseHelper helper;
    private static Context myContext;
    private static DBManager instance;

    private DBManager() {
        myContext = MyApplication.getAppContext();
        if (myContext == null)
            throw new RuntimeException("MyApplication returned null-Context");
        helper = new DatabaseHelper(myContext);

    }

    public static void init() {
        if (null == instance) {
            instance = new DBManager();
        }
    }

    public static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }
    // Some Methods to add Data and Get Data form SQL-Database

    // a Method, which creats my Objects for first App-Start; have to be called once
}

Upvotes: 0

Views: 3157

Answers (1)

jhinkley
jhinkley

Reputation: 668

Put you insert statements (or function call that points to your inserts) in the onCreate method of your DBHelper. The first time your app runs, the DBHelper will recognize that there is no database for the app, and will run the onCreate (where you should create your tables and insert seed data). After that, the onCreate should not run again unless the database gets deleted.

Upvotes: 1

Related Questions