Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

sharedpreferences - Android - How Do I Set A Preference In Code

I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume by preferences you are referring to your application's preferences and not Android phone settings.

To store preferences between runs of you application you need to do the following

  1. Create a SharedPreferences object

    SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
    

    String n identifies your preferences and the second argument is the mode they'll be accessed

  2. Instantiate an Editor object

    SharedPreferences.Editor editor = settings.edit();
    

    Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work

  3. Write your preferences to the buffer

    editor.put...(String, value)
    

    There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)

  4. Flush the buffer

    editor.commit();
    

    This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.

These preferences will by stored on the phone and will only be accessible to your application.

More documentation is here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...