Android Storage (Local storage SD card storage sharedpreference SQLite ContentProvider)

Source: Internet
Author: User
Tags sqlite database

This article originates from: http://blog.csdn.net/dt235201314/article/details/73176149

SOURCE download welcome Star (updating): Https://github.com/JinBoy23520/CoderToDeveloperByTCLer

I. Statement

This week's learning content is Android storage, requirements: Database SQLite related operations, commonly used file access methods, as well as practical learning, the main learning SQLITE,SD card file operation, sharedpreference

Second, the effect demonstration:

Three, function introduction and main content

1. Figure one completed the creation of files stored in the phone memory and read Delete, file operations related knowledge;

2. Figure II Complete the creation of files stored in the phone SD card and read Delete, file operations related knowledge;

3. Figure III completes the Sharedpreference store user preferences data, read delete data and other operations. Can be read by different apps, not encryption

4. Figure four complete SQLite to complete the player information and delete changes

Reference blog:

Player Information Management (sqlite+fragment enhancement)

And the Great God "Piggy" blog: Http://blog.csdn.net/coder_pig

Iv. Code Explanation

1. File storage

Main methods:

Demo1:

Filehelper.java

/** * <pre>* Author:jinbiao* csdn:http://my.csdn.net/dt235201314* TIME:2017/06/11* Desc: Document Assistance class* 1. File operation mode:* 1.context.mode_private: Private operation mode, default mode, represents the file is private data, can only be accessed by the app itself,* In this mode, the content of the write overwrites the contents of the source file, if you want to append the newly written content to the original file, you can use the Context.mode_append2.context.mode_append: Append operation mode: Mode checks whether a file exists, appends content to the file, or creates a new file3.context.mode_world_readable: Indicates that the current file can be read by another application. 4.context.mode_world_writeable: Indicates that the current file can be written by another application. If you want the file to be read and written by another app, you can pass in:openfileoutput ("1234.txt", context.mode_world_readable + context.mode_world_writeable);In addition, the file is placed by default in the/data/data//files directoryfor file acquisition, the Getcachedir () and Getfilesdir () methods are available in Android:The Getcachedir () method is used to get the/data/data//cache directoryThe Getfilesdir () method is used to get the/data/data//files directory* version:1.0 * </pre>*/public class Filehelper {private Context mcontext;        Public Filehelper () {} public filehelper (Context mcontext) {super ();    This.mcontext = Mcontext; }/*** This is defined as a file Save method, written to the file, so is the output stream **/public void Save (string filename, String filecontent) throws Exception {//Here we use private mode, the created file can only be accessed by the application and will overwrite the original file. FileOutputStream output = mcontext.openfileoutput (filename, Context.mode_private);  Output.write (Filecontent.getbytes ());         Writes string strings to the output stream in the form of a byte stream output.close (); Close output Stream}/*** This is defined as the method of file reading */public string Read (string filename) throws IOException {//Open file input stream FileInputStream input = Mcontext.openfile        Input (filename);        byte[] temp = new byte[1024];        StringBuilder sb = new StringBuilder ("");        int len = 0;        Read file contents: while (len = input.read (temp)) > 0) {sb.append (new String (temp, 0, Len));        }//Close input stream input.close ();    return sb.tostring (); }}

Click event Action

@Override public void OnClick (View v) {switch (V.getid ()) {r.id.Btnclean://DeleteFile (Editname.gettext (). toString ());                Editdetail.settext ("");                Editname.settext ("");            Break Case R.id.Btnsave: Filehelper fhelper = new Filehelper (mcontext);                String filename = Editname.gettext (). toString ();                String filedetail = Editdetail.gettext (). toString ();                    try {fhelper.save (filename, filedetail); Toast.maketext (Getapplicationcontext (), "Data write succeeded", Toast.Length_short). Show ();                    } catch (Exception e) {e.printstacktrace (); Toast.maketext (Getapplicationcontext (), "Data write Failed", Toast.Length_short). Show ();            } break; Case R.id.Btnread: String detail = "";                Filehelper fHelper2 = new Filehelper (Getapplicationcontext ());                    try {String fname = Editname.gettext (). toString ();                Detail = Fhelper2.read (fname);                } catch (IOException e) {e.printstacktrace (); } toast.maketext (Getapplicationcontext (), detail, Toast.Length_short). Show ();        Break }    }

Demo2



To read the flowchart:

Sdfilehelper.java

/** * <pre>* Author:jinbiao* csdn:http://my.csdn.net/dt235201314* TIME:2017/06/12* DESC:SD Card file Operation assistance class* version:1.0 * </pre>*/public class Sdfilehelper {private context context;        Public Sdfilehelper () {} public Sdfilehelper (context context) {super ();    This.context = context; }/*** method for writing files to SD card * @paramfilename* @paramfilecontent* @throwsException */public void Savafiletosd (string filename, String filecontent) throws Exception {//If the phone is plugged into an SD card and the app has permission to read and write to the SD card if (Environment.getexternalstoragestate (). Equals (Environment.media_mounted) {filename = Environment.getexternalstoragedirectory (). Getcanonicalpath () + "/" + filename;            Don't use openfileoutput here, that's the fileoutputstream output = new FileOutputStream (filename) that writes data to the phone's memory;            Output.write (Filecontent.getbytes ());            Writes string strings to the output stream in the form of a byte stream output.close (); Turn off the output stream} else Toast.maketext (context, "SD card does not exist or is not writable," Toast.)Length_short). Show (); }/*** How to read files in SD card * @paramfilename* @return* @throwsIOException */public string READFROMSD (string filename) throws IOException {StringBuilder sb = new StringBuilder (""); if (Environment.getexternalstoragestate (). Equals (Environment.media_mounted) {filename = Environment.getexternalstoragedirectory (). Getcanonicalpath () + "/" + filename;            Open file input stream FileInputStream input = new FileInputStream (filename);            byte[] temp = new byte[1024];            int len = 0;            Read file contents: while (len = input.read (temp)) > 0) {sb.append (new String (temp, 0, Len));        }//Close input stream input.close ();    } return sb.tostring (); }

Click event Actions:

@Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.Btnclean: Editdetail.settext ("");            Editname.settext ("");        Break Case R.id.Btnsave: String filename = Editname.gettext (). toString ();            String filedetail = Editdetail.gettext (). toString ();            Sdfilehelper sdhelper = new Sdfilehelper (mcontext);                try {sdhelper.savafiletosd (filename, filedetail); Toast.maketext (Getapplicationcontext (), "Data write succeeded", Toast.Length_short). Show ();                } catch (Exception e) {e.printstacktrace (); Toast.maketext (Getapplicationcontext (), "Data write Failed", Toast.Length_short). Show ();        } break; Case R.id.Btnread: String detail = "";            Sdfilehelper sdHelper2 = new Sdfilehelper (mcontext);                try {String filename2 = Editname.gettext (). toString ();            Detail = SDHELPER2.READFROMSD (filename2);            } catch (IOException e) {e.printstacktrace (); } toast.maketext (Getapplicationcontext (), detail, Toast.Length_short). Show ();    Break }}

Read and Write permissions:

<!--Create and delete file permissions in SDcard--><uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/ ><!--Write Data permissions to SDcard--><uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Demo3

Sharepreference

Use Flowchart:

Sharedpreference is to save the file as an XML map key value pair

Sharedhelper.java

/** * <pre>* Author:jinbiao* csdn:http://my.csdn.net/dt235201314* TIME:2017/06/12* Desc:sharedpreferences Data storage Assistance Class* Map key value pair form to save file* version:1.0 * </pre>*/public class Sharedhelper {private Context mcontext;    Public Sharedhelper () {} public sharedhelper (Context mcontext) {this.mcontext = Mcontext; }/*** Define a method for saving data * @paramusername* @parampasswd*/public void Save (string username, string passwd) {Sharedpreferences sp = mcontext.getsharedpreferences ("my_sp", Co ntext.mode_private);        Sharedpreferences.editor Editor = Sp.edit ();        Editor.putstring ("username", username);        Editor.putstring ("passwd", passwd);        Editor.commit (); Toast.maketext (Mcontext, "message written in Sharedpreference", Toast.)Length_short). Show (); }/*** Define a method to read SP files * @return*/Public map<string, string> read () {map<string, string> data = new hashmap<string, string> (); Sharedpreferences sp = mcontext.getsharedpreferences ("my_sp", Context.mode_private);        Data.put ("username", sp.getstring ("username", ""));        Data.put ("passwd", Sp.getstring ("passwd", ""));    return data; }}

Sharedpreferenceactivity:

public class Sharedpreferenceactivity extends Activity {private EditText editname;    Private EditText editpasswd;    Private Button btnlogin,btnshow,button_clear;    Private String strname;    Private String strpasswd;    Private Sharedhelper sh;    Private Context Mcontext;    Private Sharedpreferences sp;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.shared_preference_activity);        Mcontext = Getapplicationcontext ();        SH = new Sharedhelper (mcontext);    Intviews (); private void Intviews () {editname = (EditText) Findviewbyid (r.id.Editname); EDITPASSWD = (EditText) Findviewbyid (r.id.editpasswd); Button_clear = (Button) Findviewbyid (r.id.Button_clear); Btnshow = (Button) Findviewbyid (r.id.Buttonshow); Btnlogin = (Button) Findviewbyid (r.id.Btnlogin);                Btnlogin.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                strname = Editname.gettext (). toString ();                STRPASSWD = Editpasswd.gettext (). toString ();            Sh.save (STRNAME,STRPASSWD);        }        });                Btnshow.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) { Get the package name of the first app to get the corresponding context and need to capture the exception try {mcontext = Createpackagecontext (" Com.example.jinboy.codertodeveloperbytcler.java_demo.appdemo.ui.androiddemo ", Context.context_ignore_security);                } catch (Packagemanager.namenotfoundexception e) {e.printstacktrace (); }//The corresponding sharedpreferences SP = mcontext.getsharedpreferences ("my_sp", context) is obtained according to the context.mode_world_readable);                String name = sp.getstring ("username", "");                String passwd = sp.getstring ("passwd", "" "); Toast.maketext (Getapplicationcontext (), "Demo1 sharedpreference saved \ n Username:" + name + "\ n Password:" + PASSW D, Toast.Length_short). Show ();        }        });                Button_clear.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Sputils.clear (Mcontext); Toast.maketext (Getapplicationcontext (), "Saved information deleted", Toast.Length_short). Show ();    }        });        } @Override protected void OnStart () {Super.onstart ();        map<string,string> data = Sh.read ();        Editname.settext (Data.get ("username"));    Editpasswd.settext (Data.get ("passwd")); }}

Sharedpreference Tool Class

/** * <pre>* Author:jinbiao* csdn:http://my.csdn.net/dt235201314* TIME:2017/06/12* Desc:sharedpreference Tool class* version:1.0 * </pre>*/public class Sputils {/*** The SP file name saved in the phone */public static final Stringfile_name= "MY_SP";/*** Save Data */public static void put (context context, String key, Object obj) {sharedpreferences sp = Context.getsharedpreferenc Esfile_name, context.mode_private);        Sharedpreferences.editor Editor = Sp.edit ();        if (obj instanceof Boolean) {Editor.putboolean (key, (Boolean) obj);        } else if (obj instanceof Float) {editor.putfloat (key, (Float) obj);        } else if (obj instanceof Integer) {Editor.putint (key, (Integer) obj);        } else if (obj instanceof Long) {Editor.putlong (key, (Long) obj);        } else {editor.putstring (key, (String) obj);    } editor.commit (); }/*** Get specified data */public static object Get (context context, String key, Object defaultobj) {sharedpreferences sp = context.getshared Preferences (file_name, context.mode_private);        if (defaultobj instanceof Boolean) {return Sp.getboolean (Key, (Boolean) defaultobj);        } else if (defaultobj instanceof Float) {return sp.getfloat (key, (Float) defaultobj);        } else if (defaultobj instanceof Integer) {return Sp.getint (key, (Integer) defaultobj);        } else if (defaultobj instanceof Long) {return Sp.getlong (key, (Long) defaultobj);        } else if (defaultobj instanceof String) {return sp.getstring (key, (String) defaultobj);    } return null; }/*** Delete specified data */public static void Remove (context context, String key) {Sharedpreferences SP = context.getsharedpreferences (file_name, context.mode_private);        Sharedpreferences.editor Editor = Sp.edit ();        Editor.remove (key);    Editor.commit (); }/*** Returns all key-value pairs */public static map<string,?> GetAll (context context) {Sharedpreferences sp = context.getsharedpreferences (file_name, context.mode_private);        map<string,?> map = Sp.getall ();    return map; }/*** Delete all data */public static void Clear (context context) {Sharedpreferences sp = context.getsharedpreferences (file_name, context.mode_private);        Sharedpreferences.editor Editor = Sp.edit ();        Editor.clear ();    Editor.commit (); }/*** Check if the data for key is present */public static Boolean contains (context context, String key) {Sharedpreferences SP = context.getsharedpreferences (file_name, context.mode_private);    return Sp.contains (key); }}

Demo4:

Code Detailed reference:

Ding-Ting Academy--sqlite

Player Information Management (sqlite+fragment enhancement)

Android Basics Getting Started tutorial--6.3.1 data storage and access--the SQLite database

ContentProvider currently does not do a detailed article code reference:

Ding-Ting Academy--contentprovide

Android Basics Introductory Tutorial--4.4.1 ContentProvider

Android Basics Getting Started tutorial--4.4.2 contentprovider--ducument Provider

Android deep four components (v) Content provider Start-up process

V. File storage Application Scenario:

1. File operation can not be used for other applications, generally for the preservation of picture files;

2.SharedPreference is generally used for user information storage, can share data with other applications, generally combined with encrypted use, such as the implementation of non-landing operations;

3.SQLite lightweight database, data can be shared, generally used for structured data storage, such as the previous article mentioned in the journal Development, structured data and provide additions and deletions to change the function;

4.ContentProvider to provide a common URL for sharing data data in different apps, such as video and audio image contacts

Android Storage (Local storage SD card storage sharedpreference SQLite ContentProvider)

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.