繁体   English   中英

如何首次设置android App?

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

在我的程序中,如何首次设置SQLite数据库? 程序的结构是什么?

我能想到的唯一方法是保持第一次布尔值:

如果(isFirstInstall)setup();

这似乎很不专业。 是否完成了此类设置的onFirstInstall()调用?

您可以将布尔值存储到SharedPreferences中,并在应用程序启动时检查值(是否是第一次)。

检查sharedPreferences的文档

希望该主题对您有帮助

尝试这个

private SharedPreferences mPreferences;

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

您可以尝试使用此代码。

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

您得到布尔结果。

if (isFirstLaunch) {
    //code    
}

无需弄清楚是不是第一次启动,您可以检查数据库是否存在,并在数据库丢失时创建它。

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