Search code examples
androidpreferencessharedpreferenceskey-valuepreference

Android beginner question pre-existing simple default preferences


have been away from Android for more than a year, trying to pick up on it again, but confused about having a simple default preference.

My app relies heavily on a SQLite3 db, which has hundreds of tables. The launch activity has to build and load a good amount of data at launch.

I just need a simple way to read two strings from a preferences file. The thing is that I want to have, the very first time the application opens, two default string values.

If the user changes that I will save back to it.

Been reading two books, SharedPreferences, File I/O, etc. just that all the examples seem a tad complicated for what I need.

So, If I create a res/pref/preferences.xml all I have seen around are PreferenceScreens as the root element

For my need, I think I just need a root preference such as:

<?xml version="1.0" encoding="utf-8"?>
<Preference
 xmlns:android="http://schemas.android.com/apk/res/android">
</Preference>

how do I add two simple string key/value pairs that I would read at the very first launch, and only when needed write to it?

any help is appreciated, sorry for the noob'iness


Solution

  • I think you're over complicating what you need to do, sharedpreferences are perfect for this situation, and easily implemented. Just do the check in the onCreate() when the app starts :)

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    //"Hello World" is the name of your preferences
    SharedPreferences settings = getSharedPreferences("HelloWorld", 0);
    
    //to get a value from pref - (NAME_OF_PREF,RETURN_IF_NOT_FOUND)
    boolean enteredDetails = settings.getBoolean("details", false);
    string foo = settings.getString("foo_name","no name");
    
    //to write to them - (NAME_OF_PREF,VALUE)
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("foo_name", "Joe Bloggs");
    editor.putBoolean("details", true);
    editor.commit();
    }