你如何第一次设置值

时间:2016-06-03 11:05:04

标签: android android-sharedpreferences

我想知道如何设置仅在应用程序第一次使用时应该使用一次的值。

这似乎不起作用。我在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
    }

2 个答案:

答案 0 :(得分:3)

SharedPreferencescontains(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
}

答案 1 :(得分:0)

//declare

SharedPreferences prefs=null;

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

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



    } else {
        //run  
    }