Rasmus Rajje Josefsson Rasmus Rajje Josefsson - 1 year ago 64
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


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

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

// 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";
SharedPreferences.Editor editor = mSharedpreferences.edit();
editor.putBoolean("isItFirstTime", false); // Saving Boolean True/False
// Save the changes in SharedPreferences
editor.apply(); // commit changes

Answer Source

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



    mSharedpreferences = getApplicationContext().getSharedPreferences("MyPref1", Context.MODE_PRIVATE);
// Shared preference not present create it. First time laucnh
//SharedPreference already present. Read the value and proceed with your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download