第一次如何设置值

How do you set values for the first time

我想知道当应用程序第一次使用时,您如何设置只应使用一次的值。

这似乎不起作用。我把它放在我的 onCreate 里了。

    // SharedPreferences
    mSharedpreferences = getApplicationContext().getSharedPreferences("MyPref1", Context.MODE_PRIVATE);

    // Setting up the Switches
    mSwitchWork = (Switch) findViewById(R.id.switchWork);
    mSwitchPrivate = (Switch) findViewById(R.id.switchPrivate);


    // TODO: ONGOING
    // If its the first time in use it will set the dates to the current Month and year
    Boolean firstTime = mSharedpreferences.getBoolean("isItFirstTime", true);
    if (firstTime){
        // Just values for the first time
        mTravelType = "Private";
        mSwitchPrivate.setChecked(true);
        mSwitchWork.setChecked(false);
        SharedPreferences.Editor editor = mSharedpreferences.edit();
        editor.putBoolean("isItFirstTime", false);  // Saving Boolean True/False
        // Save the changes in SharedPreferences
        editor.apply(); // commit changes
    }

SharedPreferences 有一个 contains(String key) 方法,可用于检查是否存在具有给定键的条目。

http://developer.android.com/reference/android/content/SharedPreferences.html

例子

    mSharedpreferences = getApplicationContext().getSharedPreferences("MyPref1", Context.MODE_PRIVATE);
if(!mSharedpreferences.contains("isItFirstTime")){
// Shared preference not present create it. First time laucnh
}else{
//SharedPreference already present. Read the value and proceed with your code
}
//declare

SharedPreferences prefs=null;

//define   
prefs = getSharedPreferences("abcdef", MODE_PRIVATE);

    if (prefs.getBoolean("firstrun", true)) {
        //first time ..run only one time



    } else {
        //run  
    }