Android interview Ready the next day fifth data storage

Source: Internet
Author: User
Tags gettext sqlite sqlite database

References: http://blog.csdn.net/lmj623565791/article/details/24015867

5, Activity uses sharedpreferences to save data, the size has the wood to have the limit?

Personal Understanding: Sharedpreferences is the way to store data is not clear, the personal impression in the first line of code, the introduction of three kinds of data storage methods. Remember to include the sharedpreferences, as well as the IO stream to store the data to the phone local files, just remember the way SQLite database storage. But the way they're used has been forgotten.

So learning programming is an endorsement for me? Or programming some fixed rules or ideas, for me to have a trace of the endorsement. Suppose I default to programming as a training of thought, and really want to know whether learning programming and not learning have an essential impact on thinking.

Standard Answer: This really can't be found.

Two views: I need to take the knowledge of data storage to another study, and try to explore the ways in which my personal thinking is effective. For example, many times later I remember more deeply how to use the relevant methods. Even more wonderful I can extrapolate, can learn similar content at a higher speed. I now pessimistic feel, learning Android knowledge a lot of other is to know what features to provide, familiar with how it is used, how to use more flexible to assemble the required software, as for why these objects and methods, I think a lot of other times is due to Google at the macro level, According to the overall framework design needs to come, rookie I can only be elephant.

Knowledge Point Consolidation:

Based on the first line of code in the sixth chapter of the data storage program, specifically explaining the persistence technology, Android provides three ways to store data:

1, file storage.

2, sharedpreference storage.

3. SQLite Database Storage

In the case of file storage and sharedpreference storage, cause my memory confusion, probably the principle and use of the two storage methods almost the same, will be in the mobile phone specified folder to generate a file, and the difference is the file storage intact to copy your content files While Sharedpreference storage requires the use of key-value pairs to store data, and the system will be based on the content of key-value pairs. Generate formatted XML files in such a way as to program apes. First, XML is a canonical form of text. It is very easy to read and form a share, so I expect most of the development will choose the following way.


First, the file storage:

Just remember that one method, Openfileoutput (Filename,mode), is provided by the context and has a number of two. The first number of parameters is the file name. It does not need to specify a path, since Android will generate the file by default on the specified route, and the second parameter is in fact the setup item, which is divided into mode_private and Mode_append, which is inferred that when the program runs, the file that found the name already exists. Whether to overwrite the file directly or to append new content based on the contents of the file. The last Openfileoutput method returns a character output stream (FileOutputStream).

code example:

Uiactivity.xml:

Package Com.noodles.uipractice;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.Toast;import Java.io.bufferedwriter;import Java.io.fileoutputstream;import Java.io.ioexception;import     Java.io.outputstreamwriter;public class Uiactivity extends Appcompatactivity implements View.onclicklistener {/**     * 1, the control object is set to member variables, the General Learning Tutorial is done in this, * I feel from the Java language of the characteristics of this variable life cycle longer.    * Does not disappear after the function that created it has finished running */private EditText EditText;    Private Button btnsave;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_UI);        /** * 2, get a reference to the object of the control */EditText = (editText) Findviewbyid (R.id.edit_text);        Btnsave = (Button) Findviewbyid (R.id.btn_save); /** * 3, define the event for the button. After clicking, save the contents of the EditText.

*/Btnsave.setonclicklistener (this); } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.btn_save: String text = Edittext.gettext (). toString (); if ("". Equals (text)) {Toast.maketext (this, "text content is empty", Toast.length_short). Show (); } else {bufferedwriter bw = null; try {fileoutputstream fos = openfileoutput ("Data", mode_private); BW = new BufferedWriter (new OutputStreamWriter (FOS)); Bw.write (text); } catch (Java.io.IOException e) {e.printstacktrace (); } finally {try {if (bw! = NULL) {Bw.clo SE (); }} catch (IOException e) {e.printstacktrace (); }}} break; Default:break; } }}

Activity_ui.xml:

<?

XML version= "1.0" encoding= "Utf-8"?

><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "match _parent " android:layout_height=" match_parent " android:orientation=" vertical "> <edittext Android:id= "@+id/edit_text" android:layout_width= "match_parent" android:layout_height= "wrap_content"/ > <button android:id= "@+id/btn_save" android:layout_width= "wrap_content" android:layout _height= "Wrap_content" android:text= "Save"/></linearlayout>

Save page:

file path:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

File contents:


Second, sharedpreference storage.

1. Get the Sharedpreference object. Three different ways:

    • context "gets Haredpreference (), receives two of the parameters. The first is the file name, the second pattern has mode_private and mode_multi_process, the 1th parameter indicates that only this program can read and write to the file. The 2nd parameter indicates that multiple programs are able to read and write to the file.

    • activity getpreference (), which receives an operation mode parameter. The current active class name will be the file name, in the event should be two methods can be used, the difference is that you need not define the file name. The third method, in the same way, is called by the class name because of a static method. Can be called in whatever class. So it's just the difference between file names.

slot: Why an object is returned by means of a method call. Instead of new to create. This is probably because of the so-called design pattern, but for the advantages of these design patterns, I have no way to understand them now, which leads me to just remember that it is used. This instead adds a beginner to the puzzle of learning. 2. Call the edit () method of the Sharedpreference object to return a Sharedpreference.editor object. It should be the inner class of the sharedpreference. 3, call the Putxxx method of Sharedpreference.editor, the method receives two parameters in the way of key-value pairs. Store different types of data. XXX refers to the detailed data type. 4. Finally, the commit method is called to commit the content.
Package Com.noodles.uipractice;import Android.content.sharedpreferences;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;import Android.widget.toast;public class UIActivity extends    Appcompatactivity implements View.onclicklistener {private EditText EditText;    Private Button Btnsave,btnread;    Private TextView TextView;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_UI);        /** * 2, get a reference to the object of the control */EditText = (editText) Findviewbyid (R.id.edit_text);        TextView = (TextView) Findviewbyid (R.id.text_view);        Btnsave = (Button) Findviewbyid (R.id.btn_save);        Btnread = (Button) Findviewbyid (R.id.btn_read);         /** * 3, the button to define the event, click to save the contents of the EditText. */Btnsave.setonclicklistener (tHis);    Btnread.setonclicklistener (this); } @Override public void OnClick (View v) {sharedpreferences sharedpreferences = getsharedpreferences ("Data",        Mode_private);                Switch (V.getid ()) {case r.id.btn_save:string text = Edittext.gettext (). toString ();                if ("". Equals (text)) {Toast.maketext (this, "text content is empty", Toast.length_short). Show (); } else {//Gets the Sharedpreference object.                    Call the Getsharedpreference method of the context Sharedpreferences.editor Editor = Sharedpreferences.edit ();                    Editor.putstring ("EditView", text);                Editor.commit ();            } break; Case R.id.btn_read://Gets the value in the file by getting the GetXXX method of the Sharedpreference object.

String GetText = sharedpreferences.getstring ("EditView", "" "); Textview.settext (GetText); Break Default:break; } }}


Save page:

Path:


Content:


Android interview Ready the next day fifth data storage

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.