简体   繁体   English

如何首次设置android App?

[英]How to setup android App for the first time?

In my program how do I setup my SQLite DBs for the first time? 在我的程序中,如何首次设置SQLite数据库? What is the program structure to do this? 程序的结构是什么?

only way i can think of is to keep a first time boolean: 我能想到的唯一方法是保持第一次布尔值:

if (isFirstInstall) setup(); 如果(isFirstInstall)setup();

this seems very unprofessional. 这似乎很不专业。 Are there onFirstInstall() calls where these kind of setup is done? 是否完成了此类设置的onFirstInstall()调用?

you can store a boolean into SharedPreferences, and check the value(first time or not) when the application starts. 您可以将布尔值存储到SharedPreferences中,并在应用程序启动时检查值(是否是第一次)。

check the documentation of sharedPreferences 检查sharedPreferences的文档

hope this thread helps you 希望该主题对您有帮助

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();
    }

You can try with this code. 您可以尝试使用此代码。

Call checkFirstLaunch(); 调用checkFirstLaunch(); from onCreate(). 来自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    
}

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM