Rasmus Rajje Josefsson Rasmus Rajje Josefsson - 6 months ago 9
Android Question

How do you set values for the first time

I Wonder how you set values that only should be used once, when the application get used for the first time.

This doesn't seems to work. I've it inside my

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
}

Answer

SharedPreferences has a contains(String key) method, which can be used to check if an entry with the given key exists.

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

Example

    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
}
Comments