-1

In my program how do I setup my SQLite DBs for the first time? What is the program structure to do this?

only way i can think of is to keep a first time boolean:

if (isFirstInstall) setup();

this seems very unprofessional. Are there onFirstInstall() calls where these kind of setup is done?

kaid
  • 1,249
  • 2
  • 16
  • 32

4 Answers4

2

you can store a boolean into SharedPreferences, and check the value(first time or not) when the application starts.

check the documentation of sharedPreferences

hope this thread helps you

Community
  • 1
  • 1
Hassy31
  • 2,793
  • 3
  • 21
  • 37
2

try this

private SharedPreferences mPreferences;

    boolean firstTime = mPreferences.getBoolean("firstTime", true);
    if (firstTime) { 
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean("firstTime", false);
        editor.commit();
        showMiddleActivity();
    }
0

You can try with this code.

Call checkFirstLaunch(); from onCreate().

private boolean checkFirstLaunch() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            //int currentVersion = info.versionCode;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
            if (lastVersion == 0) {
                isFirstLaunch = true;
            } else {
                isFirstLaunch = false;
            }

        } catch (PackageManager.NameNotFoundException e) {
            Log.w(TAG, e);
        }
        return false;
    }

You get boolean result.

if (isFirstLaunch) {
    //code    
}
AndroidLearner
  • 657
  • 5
  • 10
0

Instead of figuring out wether it's the first time you start up you could check if the db is there or not and create it if it's missing.

public void createDataBase() throws IOException {
    if ( checkIfDataBaseExist() ) {
        // db exists, do nothing
    } else {
        // By calling this method and empty database will be created into
        // the default system path of your application
        this.getReadableDatabase();
        try {
            // Do you db copying here
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

private boolean checkIfDataBaseExist() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}
Peter
  • 2,165
  • 2
  • 17
  • 25