Android development tutorial-data storage (1) shared preferences, files, Network

Source: Internet
Author: User

Hi everyone!

Today, we mainly learn about the data storage mechanism of Android. There are four main methods. Today we will introduce shared preferences, files, and network. Next we will introduce the SQLite method.

As an example, it is easy:

It toilet experience
One day, I went to the computer city and suddenly felt a stomachache. Bad. You need to go to the bathroom.
Before arriving at WC, I looked up and saw an electronic card hanging above the door. I wrote: "the latest Windows Vista server WC"
I can't help but wonder: It is really high-tech!
In a hurry, fast forward. How can I close the door?
When you look up, the electronic board shows: "The user name does not exist or the password is incorrect. Please contact the Administrator ".
I paid two cents to the old man, got a password, and rushed into the toilet. However, I couldn't open the toilet lid, but I couldn't help it. I pulled it with a force pull and a card popped up on the wall: "The system prompts: you do not have access to this toilet !" Fortunately, I know a Super User Password. after entering the password in the control panel, the toilet seat is finally opened. A sigh of relief, so comfortable!
After that, I reached out to get my hand paper, but I couldn't pull it out of the box, right ......
As a result, another brand is displayed: "This tray is encrypted !"
I was dizzy. When I was impatient, someone stretched out a hand next to me: "You used Windows Vista server WC for the first time. It doesn't matter. We have shared it with our hands and paper ."
"Thank you, thank you ." While thanking me, I picked up my pants.
One punch in the toilet and another sign: "the virus has been cleared !"
Just in two steps, I only heard a bang, and the toilet lid was closed vigorously. The sign said, "connection timeout, Please refresh !"
Good risk!

Shared preferences

 1. What is shared preferences?

2. How to Use shared preferences to save data?

3. How to Use shared preferences to obtain data?

1. Shared preferences is similar to the INI file for some small configurations in winform, which is used to save some user-set parameters. For example, you can use it to save the last user modification or custom parameter settings.ProgramAnd then keep the original settings.

It is used to store the format data of the "key-value" pair. Is a lightweight key-Value Pair storage mechanism that can only store basic data types.

2. First, you need to obtain the sharedpreferences object through

Sharedpreferences sharedpre = getpreferences (activity. mode_private );

You can use the sharedpreferences. Edit () function to obtain the editing object and write data.

TheCodeAs follows:

Create a global variable s

Private string sfkey = "isplay ";

/**  
* Activity. mode_private, // default operation mode, which indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file, you can use activity. mode_append
Activity. mode_world_readable, // indicates that the current file can be read by other applications,
Activity. mode_world_writeable, // indicates that the current file can be written by other applications;
// If you want the file to be read and written by other applications, You can input activity. mode_world_readable + activity. mode_world_writeable.
Activity. mode_append // This mode checks whether the file exists and appends the content to the file. Otherwise, a new file is created.
*/
@ Override
Public Void Onclick (view v ){
// Get sharedpreferences object
Sharedpreferences sharedpre = getpreferences (activity. mode_private );
// Sharedpreferences sharedpre = getsharedpreferences ("AAA", activity. mode_private );
// Get the sharedpreferences Edit object
Sharedpreferences. Editor editor = sharedpre. Edit ();
If (Rb0.ischecked ())
Editor. putboolean (sfkey, True ); // Add and save the data key-Value Pair format
Else
Editor. putboolean (sfkey, False );
Editor. Commit (); // Save data
Toast. maketext ( This , "Saved successfully", Toast. length_short). Show ();
}

 

3. The data retrieval code is as follows:

Sharedpreferences sharedpre = getpreferences (activity. mode_private );
//The first parameter indicates that the file name to be created will create an AAA. xml
//Sharedpreferences sharedpre = getsharedpreferences ("AAA", activity. mode_private );
If(Sharedpre. getboolean (sfkey,False))
Rb0.setchecked (True);
Else
Rb1.setchecked (True);

 

To share variables between different activities of an application, use getsharedpreferences (),If you only want to save the status of an activity and do not need to share it with other activities, you can use activity. getpreference ().

Getpreferences () only requires one mode parameter, while getsharedpreferences () also requires another name.

Four storage permissions for sharedpreferences

Activity. mode_private, // default operation mode, which indicates that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file, if you want to append the newly written content to the original file, you can use activity. mode_append

Activity. mode_world_readable, // indicates that the current file can be read by other applications.

Activity. mode_world_writeable, // indicates that the current file can be written by other applications;

Activity. mode_append // This mode checks whether the file exists and appends the content to the file. Otherwise, a new file is created.

// If you want the file to be read and written by other applications, You can input activity. mode_world_readable + activity. mode_world_writeable.

View the files generated by preferences (select the current file and export this file. You can see that the stored data is actually an XML node)

You can do an exercise, for example, to consolidate what you have learned.

 

Files

1. What is file data storage?

2. What is properties?

3. How to save data

4. How to obtain data

1. file is to record the objects to be saved in the form of a file. When you need the data, read the file to obtain the data. Because Android uses the Linux core, files in the Android system are also in the form of Linux.

In Android, you can create a file to save data in the storage of the device or an external storage device. By default, files cannot be shared among different programs.

2. properties can inherit properties from hashtable and be understood as a hashtable. However, the only difference is that the "key-value" corresponding to properties must be a string type of data. Files Data Storage Uses properties in combination with fileinputstream or fileoutputstream to write files.

3. The data saving code is as follows:

Create global variables

Private string sfkey = "isplay ";

 Public  Boolean Save ()
{
Properties Properties = New Properties ();
If (Rb0.ischecked ())
Properties. Put (sfkey, String. valueof ( True )); // The saved key-value must be in the string format.
Else
Properties. Put (sfkey, String. valueof ( False ));
Try {
// You can use the Linux file type or the Windows file type to save the file format.
// Fileoutputstream file write stream
Fileoutputstream stream = This . Openfileoutput ("filesdata. cfg", context. mode_private );
Properties. Store (stream ,"");
} Catch (Exception e ){
System. Out. println (E. getmessage ());
E. printstacktrace ();
Return False ;
}
Return True ;

}

 

4. The data retrieval code is as follows:

     Public   Void Load ()
{
Properties Properties = New Properties ();
Try {
Fileinputstream stream = This . Openfileinput ("filesdata. cfg ");
Properties. Load (Stream ); // The Code has an explanation of the properties object method. Let's take a look.
// You can use proPerties. getproperty () to obtain the required value.
Boolean Result = Boolean. valueof (properties. getproperty (sfkey ));
If (Result)
Rb0.setchecked ( True );
Else
Rb1.setchecked ( True );
}Catch (Exception e ){
// Todo: handle exception
}

}

Common Methods

 /* Common method
* • Return Value: String
Method: getproperty (string name, string defaultvalue)
Explanation: Search for attributes by specifying "name", that is, key. Parameter 2 is the default value. That is, if the attributes in the file cannot be found through the key, the default value is returned.

• Return Value: String
Method: getproperty (string name)
Explanation: the specified "name" is the key, and the search attribute does not return the default value.

• No Return Value: void
Method: List (printstream out)
Explanation: Use printstream to list readable attributes

• No Return Value: void
Method: List (printwriter writer)
Explanation: Use printstream to list writable attributes

• No Return Value: Synchronized void
Method: load (inputstream in)
Explanation: Load properties from the specified "inputstream", that is, the output stream.

• No Return Value: Synchronized void
Method: loadfromxml (inputstream in)
Explanation: loads a properties in XML format from the specified "inputstream", that is, the output stream.

• Return Value: enumeration <?>
Method: propertynames ()
Explanation: All attribute names contained in the file are returned.

• No Return Value: void
Method: Save (outputstream out, string comment)
Note: This method is outdated and is not recommended for Google. This method ignores any Io exceptions. Therefore, unnecessary exceptions may occur during actual operations.

• Return Value: Object
Method: setproperty (string name, string value)
Explanation: Set the attribute and save the attribute of a "key-value" pair.

• No Return Value: Synchronized void
Method: store (outputstream out, string comment)
Explanation: Open the corresponding program file through fileoutputstream, and save the data packaged in properties through store. The remarks here can be empty.

• No Return Value: void
Method: storetoxml (outputstream OS, string comment)
Explanation: Use fileoutputstream to open the corresponding program file and write the packaged data to the XML file.

• No Return Value: Synchronized void
Method: storetoxml (outputstream OS, string comment, string encoding)
Explanation: Open the corresponding program file through fileoutputstream and write the packaged data to the XML file. The third parameter can specify the encoding.

* */

View the generated file

 

Network

Saving data in this way is relatively cumbersome and not practical. This method is not used in development, so it is not recommended for everyone. If you are interested, you can search for relevant materials to learn more.

The code is uploaded to Beijing tianshengda Technology Co., Ltd. You are welcome to download it.

Related Article

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.