Does Android provide smth. like that OR do I have to check every time during start of my app "Oh, am I freshly installed? Do I have to initialize the Shared Preferences now?"
It is a good idea to check for the preference file existence anyway if you depend on certain critical values.
If you worry that user can clear data of your app, consider using this flag inside tag <application>
of your AndroidManifest.xml:
android:manageSpaceActivity="path.to.your.activity"
Then, instead of "Clear data" button, it will be "Manage space". And your activity will be called when the user click that button.
Generally, you should do as Select0r mentioned. All other "default xml/ ..." are not worth for the time you maintain your project.
You can just get any key/value-pair from the preferences and provide a default-value in the method-call, like this: prefValue = prefs.getString("prefName", "defaultValue");
, there's no need to initialize.
If the key ("prefName" in this case) doesn't exist in the preferences, the default-value will be used. Once you let the user change the prefs, the PreferencesActivity will take care of writing the changed values back to the prefs.
Here's a good tutorial on Android Preferences:
http://www.kaloer.com/android-preferences
You can check for the existence of the shared preference file at the start of your main activity, and write the default preferences if the file doesn't exist. That way, preferences will always be written on the first run after install, since after that the file will already exist.
The file is located at /data/data/com.your.package.name/shared_prefs/something.xml
, where something
is the first parameter passed to getSharedPreferences
.
Here is some example code that does this:
const val PREFERENCES_NAME = "preferences"
fun createDefaultPreferences(context: Context){
// Check if the app is newly installed by checking if the preference file we're about to write to exists
// This file does not exist by default for newly installed apps, but is created as soon as you write preferences to it as is done below
val isNewlyInstalled = File("/data/data/" + context.getPackageName() + "/shared_prefs/" + PREFERENCES_NAME + ".xml").exists()
// If it's newly installed, write the preferences
if(isNewlyInstalled){
context.getSharedPreferences(PREFERENCES_NAME, AppCompatActivity.MODE_PRIVATE)
.edit()
.putString("Your key", "Your value")
.apply()
}
}
class MainActivity: AppCompatActivity() {
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// If the app is newly installed, this will write the default preferences, otherwise it will do nothing
createDefaultPreferences(this)
...
}
...
}
Note that this will trigger if the user has cleared the app's data in addition to when the app is newly installed, but that's probably a good thing because if the app's data is cleared everything should be reset to default.
© 2022 - 2025 — McMap. All rights reserved.