Disclaimer: The book "Secrets of Android Application Development", which records the logs of the book, references the relevant code and summary, and has no commercial use, it is completely a record of self-learning, and many problems will inevitably occur in learning just now. If there are any mistakes, please criticize them a lot.
After learning the basic controls and layout, I skipped the chapter on game programming and started learning about data operations on Android. The preparation for game programming is later, after learning the basic controls and related event operations, follow the web development process, that is, data involving data operations, includingFiles, network resources, and databasesOperation, this content, I learned several times, because after all, each application does not exist independently, and data operations are inevitable. Let's get started.
I. sharedpreferences in data storage
I personally think sharedpreferences is an init configuration file for a program, or a cookie in Web development. It stores key-value pairs, and sharedpreferences in Android also provides get methods for various data types. Note: sharedpreferences is an interface, and the preferences object is generally obtained through the getpreferences method. You can use the Edit () method of the preferences object to obtain the editing object.
// Get the preferences object of the activity. sharedpreferences uistate = getpreferences (0); // get the Edit object sharedpreferences. Editor editor = uistate. Edit ();
You can update and maintain the data in the editing object.
Instance analysis: This program is a music playing program. If the music is still playing when you exit the program by following the return key, save the current music status and enable the music status at the next startup.
Key code of music playing midiplayer:
Public mediaplayerplayermusic = NULL; private contextmcontext = NULL; Public midiplayer (context) {mcontext = context;}/* play music */Public void playmusic () {/* load the music in the resource */playermusic = mediaplayer. create (mcontext, R. raw. start);/* set whether to play cyclically */playermusic. setlooping (true); try {playermusic. prepare (); // prepare for synchronization, no return value} catch (illegalstateexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace (); } Playermusic. Start ();}/* Stop and release music */Public void freemusic () {If (playermusic! = NULL) {playermusic. Stop (); playermusic. Release ();}}
Key code of sharedpreferencesactivity:
Public void oncreate (bundle savedinstancestate ){...... mmidiplayer = new midiplayer (this); // gets the preferences object of the activity. sharedpreferences settings = getpreferences (activity. mode_private); // obtain the value. mbmusic = settings. getboolean ("bmusic", false); If (mbmusic) {mtextview. settext ("current music status: On"); mbmusic = true; mmidiplayer. playmusic ();} else {mtextview. settext ("current music status: Off") ;}} public Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) {/* Here we save the data when exiting * // get the preferences object of the activity. sharedpreferences uistate = getpreferences (0); // get the edited object sharedpreferences. editor editor = uistate. edit (); Editor. putboolean ("bmusic", mbmusic); // Add a value // submit and save the editor. commit (); If (mbmusic) {mmidiplayer. freemusic ();} This. finish (); Return true;} return Super. onkeydown (keycode, event );}
[Extended learning]
It should be emphasized that preferences data cannot be directly shared among multiple programs.
1. The haredpreferences file is actually stored in a file. For example, switch to the ddms view,
Each time a project is installed in the simulator, a folder is generated under the Data/data directory. If sharedpreferences is used, a shared_prefs folder is created,
The content of sharedpreferencesactivity. xml corresponding to this program is:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><boolean name="bmusic" value="true" /></map>
2 sharedpreferences
Internal class
Interface sharedpreferences. editor -- interface used to modify the value of the sharedpreferences object.
Interface sharedpreferences. onsharedpreferencechangelistener -- the interface defines a callback function called when the preference is changed (shared preference.
Common Methods
Public Abstract BooleanContains(String key) -- determines whether preferences contain a preference.
Parameter: name of the preference to be judged by the key
Returned value: If a preference exists in peferences, true is returned. Otherwise, false is returned.
Public abstract sharedpreferences. EditorEdit()
Create a new editor object for preferences. With this object, you can modify the data in preferences and submit the data to sharedpreferences through atomicity. (Note: atomicity-submit as a whole, atomicity)
Note: If you want to display it in sharedpreferences in real time and modify it through the editor object, you must call the Commit () method.
Returns a new sharedpreferences. Editor instance that allows you to modify values in the sharedpreferences object.
Public abstract Map <string,?>Getall() -- Get all values in preferences and return a map containing a key-Value Pair in a column of preferences
Exception: NULL pointer exception (nullpointerexception)
Public Abstract Boolean getboolean (string key, Boolean defvalue) -- obtains a Boolean value from preferences.
Parameter: name of the preference obtained by the key
Defvalue: the default value returned when this preference does not exist.
Returned value: if preference exists, the value of preference is returned; otherwise, the value of defvalue is returned. If the preference type with this name is not a boolean type, classcastexception is thrown.
Exception: classcastexception
Public abstract float getfloat (string key, float defvalue)
Public abstract intGetint(String key, int defvalue)
Public abstract longGetlong(String key, long defvalue)
Public abstract stringGetstring(String key, string defvalue)
Public abstract voidRegisteronsharedpreferencechangelistener(Sharedpreferences. onsharedpreferencechangelistener listener)
Register a callback function and call it when a preference changes.
Public abstract voidUnregisteronsharedpreferencechangelistener(Sharedpreferences. onsharedpreferencechangelistener listener)
Deregister a previously (registered) callback function
Ii. Data Storage files
Some programs need to save data to the corresponding files, but note that files cannot be shared among multiple programs. You can use the openfileoutput method to open a file.
Instance analysis: the results are the same as those in the above sharedpreferences example.
Key source code:
Void load () {/* build properties on Object */properties Properties = new properties (); try {/* Development file */fileinputstream stream = This. openfileinput ("music. cfg ");/* Read File Content */properties. load (Stream);} catch (filenotfoundexception e) {return;} catch (ioexception e) {return;}/* Get Data */mbmusic = Boolean. valueof (properties. get ("bmusic "). tostring ();}/* save data */Boolean save () {properties Properties = new properties ();/* package the data into properties */properties. put ("bmusic", String. valueof (mbmusic); try {fileoutputstream stream = This. openfileoutput ("music. cfg ", context. mode_world_writeable);/* write the packaged data to the file */properties. store (stream, "");} catch (filenotfoundexception e) {return false;} catch (ioexception e) {return false;} return true ;}
[Extended learning]
Using files to store data also stores data in files under the corresponding data/data directory,
The content of music. cfg is:
##Wed Nov 02 10:06:38 GMT+00:00 2011bmusic=true
Iii. Web data operations for data storage
Many programs store data and other information to the service through the network, and also read relevant data from the server to themselves. The most typical example is sending and receiving emails on a mobile phone. Of course, to use the network, you must first ensure that the network of the mobile phone is connected.
Here I have configured the binding of the 163 mailbox in the simulator, as shown in the left figure. The intermediate figure shows the settings for receiving servers, and the right figure shows the settings for sending servers.
The following two examples are respectively Data Writing and data retrieval,
1. Send email from function (write data)
Key source code:
Public Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) {// save data when exiting the application // URI of the email Sending address uri = Uri. parse ("mailto: jercy1987@163.com"); // create intentintent intent = new intent (intent. action_sendto, Uri); // sets the subject intent of the email. putextra (Android. content. intent. extra_subject, "data backup"); // sets the mail content intent. putextra (Android. content. intent. extra_text, "Count this time:" + micount); startactivity (intent); this. finish (); Return true;} return Super. onkeydown (keycode, event );}
:
2. Get data from the webpage
Hosts file.
Key source code:
String mystring = NULL; try {/* defines the URL to be accessed */URL uri = new URL ("http: // 192.168.8.64: 8080/testweb/android.html "); /* Open the URL Connection */urlconnection ucon = Uri. openconnection ();/* obtain inputstream from the above link */inputstream is = ucon. getinputstream (); bufferedinputstream Bis = new bufferedinputstream (is); bytearraybuffer BAF = new bytearraybuffer (100); int current = 0; /* always read the end Of the file */while (current = bis. read ())! =-1) {BAF. append (byte) Current);} mystring = new string (BAF. tobytearray ();} catch (exception e) {mystring = E. getmessage ();}/* set the information to textview */TV. settext (mystring );
Program running:
[Extended learning ]:
(1) android must have:
<Uses-Permission Android: Name = "android. Permission. Internet"/>
Otherwise, the system prompts:
Permission denied
(2 ),
/* Define the URL to be accessed */
URL uri = new URL ("http: // 192.168.8.64: 8080/testweb/android.txt ");
/* Open the URL Connection */
Urlconnection ucon = URI. openconnection ();
If it is a local machine, localhost or 127.0.0.1 cannot be used. Otherwise, the connection will fail.
(32.16.html test HTML file android.html
<HTML>
Android gets the HTML source code instead of the content, because it does not have a parser and is garbled.
The above data storage will be learned first. The next article focuses on database operations.