RedShirt
RedShirt

Reputation: 864

Android: App keeps prepopulating the sqlite database

I currently have an activity that contains a shared preference to tell whether the sqlite database has been pre populated or if it needs to be. However my application populates every time the activity is created.

I currently have the following methods for the shared preferences:

public void checkDB() {
        SharedPreferences sharedPref = MainActivity.this
                .getPreferences(Context.MODE_PRIVATE);
        Editor editor = sharedPref.edit();
        editor.putBoolean("CHECK", true); // Storing boolean - true/false
        editor.commit(); // commit changes
        prepopulate();

    }

    public void isChecked() {
        boolean setup = false;
        SharedPreferences sharedPref = MainActivity.this
                .getPreferences(Context.MODE_PRIVATE);
        setup = sharedPref.getBoolean("CHECK", true); // getting boolean
        if (setup = false) {
            checkDB();
        } else {

        }

Here is how I call them in the onCreate method:

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkDB();
        isChecked();
        loadListView();
        registerListClickCallback();

I am sure I have something wrong with one of the booleans in the shared preferences methods. Just incase it helps, here is my loop for pre populating the database fields:

public void prepopulate() {
        Locker setup = new Locker(this);
        for (int x = 0; x < 46; x++) {
            setup.open();
            String lockerNumber = "Locker" + x;
            setup.createLockerEntry(lockerNumber, 0);
            setup.close();
        }
    }

Upvotes: 0

Views: 88

Answers (2)

laalto
laalto

Reputation: 152927

The reason for the re-population is that you call checkDB() unconditionally as mentioned in @Kedamath.

However, consider using just plain old SQLiteOpenHelper and put any prepopulation code in its onCreate(). The framework calls that method exactly once when the database file didn't exist and the tables and any prepopulated data need to be created.

Upvotes: 1

Lucifer
Lucifer

Reputation: 29670

You are calling checkDB() method in isChecked() method, hence you dont need to call it onCreate()

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openedLockers = (Button) findViewById(R.id.bOpenLockers);
        closedLockers = (Button) findViewById(R.id.bClosedLockers);
        openedLockers.setOnClickListener(this);
        closedLockers.setOnClickListener(this);
        checkDB();                                      // remove or comment this line 
        isChecked();
        loadListView();
        registerListClickCallback();

Upvotes: 1

Related Questions