Android Learning notes---data storage and access (File,sdcard,sharedpreferences,sqlite)

Source: Internet
Author: User
Tags sqlite database

One using files for data storage 1.context.openfileoutput () method writes the file contents            The Openfileoutput method can be used to output data to a file in a contextual context         Sample code:            public static void Filestorage (context context) {              Try {                   fileoutputstream Fos = con Text.openfileoutput ("Filedata.txt", context. mode_private);                      fos.write ("File storage"). GetBytes ());                      fos.flush ();    &N Bsp              fos.close ();                     catch (Exception e) {                   e.printstacktrac E ();             } } openfileoutput () the first parameter of the method is used to specify the file name and cannot contain the path delimiter "/", if the file does not exist, it will be created automatically, save the file created in the/data/data/package name/files directory such as:/data/data/cn.itcast/files/itcast.txtopenfileoutput () The second parameter of the method is used to specify the mode of operation, with four modes:  context.mode_private    =  0context.mode_append    =  32768context.mode_world_readable =  1context.mode_world_writeable =  2  Context.mode-private: As the default mode of operation, which means that the file is private data, can only be accessed by the application itself, in which the content of the write overwrites the contents of the original file, if you want to append the newly written content to the source file, you can use Context.mode_ Append context.mode-append: The schema checks whether the file exists, appends content to the file, or creates the file  context.mode_world_readable and Context.mode_ World_writeable is used to control whether other apps have permission to read and write to the file  context.mode_world_readable:   Indicates that the current file can be read by another application  context.mode_ World_writerable:     Indicates that the current file can be written by another application       If you want the file to be read and written by another application, you can pass in:    Openfileoutput ("Filestorage.text", Context.mode_world_readable + context.mode_world_writeable);     Android has its own security model, and when the application (. apk) is installed, the system assigns him a userid, and when the app is going to access other resources, such as when visiting a file, a UserID match is required.     By default, any file created by the app, Sharepreferences, the database should be private (bit/data/data/Package name/files), other programs cannot be accessed. Unless you specify context.mode_world_readable or context.mode_world_writeable at creation time, only such other programs can access them correctly.       2. read file contents         If you open a file stored in the/data/data/package name/files directory, you can use the Openfileinput () method provided by the activity             fileinputstream FIS = context.openfileinput ("FileStorage2.txt");        & nbsp  bufferedreader br = new BufferedReader (new InputStreamReader (FIS));              string data = Br.readline ();          &NBSP;SYSTEM.OUT.PRINTLN ("Data:" + data);  or use the absolute path of the file directly:    filename File = new file ("/data/data/package name/files/file name"):    FileInputStream fis = new Filei Nputstream (file);         bufferedreader br = new BufferedReader (New InputStreamReader ( FIS));              string data = Br.readline ();          &NBSP;SYSTEM.OUT.PRINTLN ("Data:" + data);     for private files can only be accessed by the app that created the file, if you want the file to be read and written by another app, you can create the file Specify Context.mode_world_readable and CONTEXT.MODE_WORLD_WRThe Iterablez permission  activity also provides the Getcachedir () and Getfiledir () methods      Getcachedir () methods for obtaining the/data/data/package name/ The cache directory  -----Get cached information      Getfiledir () method is used to get the/data/data/package name/files directory  ======================= ===========================================================  Second, the file is stored in SDcard 1. Store to SDcardUsing the Activityd openfileoutput () method to save files, files are stored in the mobile phone space, general phone storage hole home is not very large, store write small file ok, but generally can not store large files, such as video, etc. in the simulator using SDcard, You need to create an emulator with SDcard to access SDcard in the program, you need to request permission to access SDcard. // permissions to hang and uninstall SDcardAndroid.premission.MOUNT_UNMOUNT_FILESTSTEMS// Write permissions to external storage devices android.permission. Write_external_storage to store files to SDcard, the program must first verify that the phone has sdcard presence and can read and write. Note: Access to SDcard must include access to SDcard in Androidmanifest.xml      if (Environment.getexternalstoragestate () equals (environment.media_mounted)) {       //Determine if there is an SD card Environment.getexternalstoragestate () method to get SDcard status,       // If the phone is loaded with sdcard and can read and write, the method returns a state equal to environment.media_mounted.           file sdcarddir = Environment.getexternalstoragedirectory (); Get SDcard card path        file file = new file (Sdcarddir, "SdCardStorage.txt");          try {           if (!file.exists ()) {            &N bsp;//Create the file if it does not exist              file.createnewfile ();       } &N Bsp             FileOutputStream fos = new FileOutputStream (file);      &NBS P Fos.write ("SD card Storage". GetBytes ());        Fos.flush ();        fos.close ();  & nbsp &nbsP  } catch (Exception e) {       //TODO auto-generated catch block        &NB Sp   E.printstacktrace ();       }        }     2. Extracting data from SDcard   Add permission to extract data from SDcard: Android.permission.READ_EXTERNAL_STORAGE   if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { //Determine if memory card exists File Sdcarddir = Environment.getexternalstoragedirectory (); File File = new file (Sdcarddir, "sdCardStorage.txt");     try { FileInputStream fis = new FileInputStream (file);     bufferedreader br = new BufferedReader (new InputStreamReader (FIS));     String data = Br.readline ();     System.out.println ("Data:" + data);     fis.close (); br.close ();   } catch (Exception e) { //TODO auto-generated catch block e.printstacktrace ();                }       }================================================================================== third, using sharedpreferences for data storage   1. Storing Data     The Sharedpreferences class, a lightweight storage class, is ideal for saving software configuration parameters. Using Sharedpreferences to save data, which is essentially storing data with an XML file, the file is stored in the/data/data/package name/shared_prefs directory      commonly used to save: QQ login information, Simple configuration information, status, identification, etc.        Sharedpreferences sp = context.getsharedpreferences ("Sharedpre", context. Mode_private);       Editor editor = Sp.edit (); Get editor       editor.putstring ("Spstorage", "Sharedpreferences Way to save data");      Editor.commit (); The XML file submitted   generated is as follows:                <?xml version= ' 1.0 ' encoding= ' Utf-8 ' standalone= ' yes '?>        <map>            <string N Ame= "Spstorage" >sharedpreferences way to save data </string>        </map>     Because Sharedpreferences is behind the use of XML files to save data, the first parameter of the Getsharedpreferences (Name,mode) method is used to specify the name of the file. The name is followed by the suffix. xml, and the suffix is automatically added by Android. The second parameter of the method specifies the mode of operation of the file, there are four modes of operation, that is, the four modes written earlier.      If you want SharedprefThe XML file used behind Erences can be read and written by other applications and can specify Context.mode_world_readable and context.mode_world_writeable permissions.      The activity also provides another getpreferences (mode) method operation Sharedpreferences, which defaults to the name of the file using the current class without the package name.      2. Accessing data in the Sharedpreferences  Sharedpreferences sp = context.getsharedpreferences ("Sharedpre", context.  Mode_private);  String data = sp.getstring ("Spstorage", null);     SYSTEM.OUT.PRINTLN ("Data:" + data); Sp.getstring (key, Defvalue); method The first parameter is the key, the corresponding value is found according to key, and if not, the second parameter is returned Defvalue (default) four, SQLite database store SQLite     is a lightweight database, is to comply with acid (atomicity, consistency, isolation, durability) of the associated database management system, more used in embedded development. SQLite data type: typelessness (Type of object), you can save any type of data to any column of any table you want to save, but it also supports common types such as: Null,varchar,text,integer,blog,clob .... Wait a minuteThe only exception is: Integer primary key This field can only store 64 as an integer In Android, a Sqliteopenhelper abstract class is provided that is used to manage the database version that is commonly used in this class: OnCreate This method is called when the database is created (the first time the connection gets the database object is executed) Onupgrade This method is called when the database is updated (when the version number is changed) the OnOpen database executes every time the database is opened (oh, every time you open it, after the OnCreate, Onupgrade method 1. Use Sqlitedatabase to manipulate the SQLite databaseAndroid provides a class called Sqlitedatabase, which encapsulates APIs that manipulate databases, which can be used to add (Create), query (Retrieve), update, and delete (delete) data. These actions are referred to as ( CRUD)      Execsql () method can perform SQL statements with change behavior such as INSERT, delete, update, and create table; Rawquery () method is used to execute a SELECT statement (querying query).  sqliteopenhelper Abstract class:     public class Mysqliteopenhelper extends Sqliteopenhelper {   & nbsp      public Mysqliteopenhelper (context context) {                &N Bsp Super (context, "database.db", NULL, 1);         }         &NBSP;/**&NBS P          * database creation call            */         @ override         public void OnCreate (Sqlitedatabase db) {        &NBSP;&NBSP ;          String sql = "CREATE TABLE database (_id integer primary key autoincrement,name Varcha R (), age varchar ()) ";          db.execsql (SQL);         } & nbsp     &NBSP  /**          * Database Update call           */        &NB SP; @Override          public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {&N Bsp        //TODO auto-generated method stub          }     }  database additions and deletions:          /**          * Database Help class     &NB Sp     */         private mysqliteopenhelper helper;         &NBS P;public Databaseutils (Context context) {          helper = new Mysqliteopenhelper (context); nbsp        }          /**          * Insert data into the database           */         public void Insert () {          & nbsp   Sqlitedatabase db = Helper.getwritabledatabase ();              String sql = "Insert int o Database values (null, ' Zhangsan ', ' $ ') ";              db.execsql (SQL);    & nbsp         db.close (); }          /**        &NBSP ; * Update data in database           */         public void update () {    &NBSP ;         Sqlitedatabase db = Helper.getwritabledatabase ();            &NB Sp Contentvalues values = new Contentvalues ();              values.put ("name", "Lisi"); &NB Sp             db.update ("database", values, "name =?", new String []{"Zhangsan"});  &nbs P           db.close ();     }              / **              * Query data in the database               */  &NB Sp      public void query () {              Sqlitedatabase db = Helper.getrea Dabledatabase ();              String sql = "Select Name,age from Database";  &nbsp ;           CURSOR cursor = db.rawquery (sql, NULL);              while (cursor = null && cursor.movetonext ()) {//Cursor NOT NULL prevents a null pointer exception MoveToNext () moves to the next line      & nbsp             String name = cursor.getstring (0); Get the value of the first column, the index of the first column starting from 0                   int age = Cursor.getint (1); Get the second class of values                   SYSTEM.OUT.PRINTLN ("Name:" + name + "," + "age : "+ age";         }         Cursor.close ();          db.close ();  }          /**          * Delete data from the database           */      &N Bsp  public void Delete () {              Sqlitedatabase db = Helper.getwritabledatabase ();              db.delete ("database", NULL, NULL);          & nbsp   Db.close ();     }     cursor is a result set cursor that is used for random access to the result set, similar to the role of resultset in JDBC. Use the MoveToNext () method to move a cursor from the current row to the next row, or true if it has been moved to the last row and the result is false. The cursor also uses the usual movetoprevious () method (used to move the cursor from the current row to the previous row, if it has been moved to the first row of the result set, the return value is false, otherwise true), Movetofirst () Method (used to move the cursor to the first row of the result set, if the result set is empty, the return value is false, otherwise true), and the Movetolast () method (used to move the cursor to the last row of the result set, or true if the result set is empty);   manipulating SQLite databases with transactions   Sqlitedatabase db = null; try { db = Helper.getwritabledatabase (); db.begintransaction ();//Open Transaction String sql = "INSERT into database values (NULL, ' Zhangsan ', '") "; db.execsql (SQL); db.execsql ("Update database set name=?") Where age=? ", New object[]{" Wangwu ", ()); db.settransactionsuccessful ();//Call this method to commit the current transaction when it executes to the Endtransaction () method, and if this method is not called, the transaction is rolled back }finally{ if (db! = null) { db.endtransaction ();//The end of the transaction flag that determines whether the transaction is committed or rolled back            }       } db.close ();Using the Sqlitedatabase BeginTransaction () method to open a transaction, the program executes to the Endtransaction () method when the flag of the transaction is checked for success if the program executes to Endtransaction () Method before the Settransactionsuccessful () method is called to set the transaction flag to successful, the transaction is committed, and the transaction is rolled back if the settransactionsuccessful () method is not called

Android Learning notes---data storage and access (File,sdcard,sharedpreferences,sqlite)

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.