Android Basics (14)

Source: Internet
Author: User

Take a little book, remember?

    • Take a little book, remember?
      • Brief introduction
      • Body
      • Extended Reading

Target group: Android Beginner without foundation
Knowledge Points: Simple use of the Sharedpreferences class
Goal: Record simple key-value pairs of data

Brief introduction
    • Creation of Sharedpreferences

    • Sharedpreferences writing and reading of data

Body

1. First we need to create a Sharedpreferences class object, the simplest code is as follows

SharedPreferences preferences= getPreferences(Context.MODE_PRIVATE);
    • The definition of the Getpreferences method comes from the activity class

    • Context.mode_private constants are configured by default, and in addition to mode_world_readable and mode_world_writeable

2. For writing data about Sharedpreferences, the following example shows how to save a simple int type key-value pair

SharedPreferences preferences= getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = preferences.edit();editor.putInt("index"1);editor.commit();
    • Sharedpreferences can store a variety of data types, in addition to commonly used types, also supports Stringset storage

    • When the data is written, remember to call Editor.commit ()

3. For sharedpreferences data read, the following example shows how to read an int type from the Preferences object, named index
of data

SharedPreferences preferences= getActivity().getPreferences(Context.MODE_PRIVATE);int0;intindex = preferences.getInt("index", defaultIndex);
    • The first parameter of the Preferences.getint method is the key name of the value that you want to get, and the second parameter is the default value when the "index" parameter does not have a corresponding value
Extended Reading
    1. Save the file

Android Basics (14)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.