The first line of code reading notes

Persistence technique

  • File storage
  • SharedPreference storage
  • Database storage

File storage

  • The stored content is not formatted in any way
  • Suitable for storing some simple text data or binary data

Data is stored in a file

  • ContextClass provides aopenFileOutput()Method to store data to a specified file
  • Receive two parameters
    • The first parameter is the file name

      Cannot include path, all files are stored to default/data/data/<package name>/files/directory
    • The second parameter is the mode of operation of the file

      MODE_PRIVATE: Default operation mode. If a file with the same name exists, the written content overwrites the content of the original file

      MODE_APPEND: If a file with the same name exists, append the content to the source file. If the file does not exist, create a new file
  • Returns aFileOutputStreamobject
  • FileOutputStream->OutputStreamWriter->BufferedWriter

    throughBufferWriterWrites text content to a file
public void save(String inputText) { FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer ! = null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); }}}Copy the code
  • Tools->Android->Android Device Monitor View/export files

Read data from a file

  • ContextClass provides aopenFileInput()Method to read data from a file
  • Only one parameter is received: the file name to read

    The system will automatically arrive/data/data/<package name>/files/Directory to load files
  • Returns aFileInputStreamobject
  • FileInputStream->InputStreamReader->BuffereedReader
  • Can be achieved byBufferedReaderLine by line, the text content is read into the StringBuilder object
public String load() { FileInputStream in = null; BufferedReader reader = null; StringBuilder content = new StringBuilder(); try { in = openFileInput("data"); reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) ! = null) { content.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader ! = null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); }Copy the code
  • Load the text of the file into EditText
String inputText = load(); if (! TextUtils.isEmpty(inputText)) { edit.setText(inputText); edit.setSelection(inputText.length()); Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show(); }Copy the code
  • setText(): fills the string into the EditText
  • SetSelection(): Moves the input cursor to the end of the text
  • TextUtils.isEmpty(): Returns true if the string passed is null or equal to an empty string;

SharedPreferences storage

  • Uses key-value pairs to store data
  • Supports storage of many different data types

Store the data in SharedPreferences

  • Three ways to get a SharedPreferences object
    1. ContextOf the classgetSharedPreferences()methods
      • Receive two parameters

        The first parameter is used to specify the name of the SharedPreferences file, or create one if the specified file does not exist

        SharedPreferences files are stored/data/data/<package name>/shared_prefs/The second parameter in the directory is used to specify the operation modeMODE_PRIVATEOptional (Default mode, same as passing 0)

        Indicates that only the current application can read and write the SharedPreferences file (other modes are deprecated)
    2. ActivityIn the classgetPreferences()methods
      • Only one operation mode parameter is received
      • Automatically use the name of the currently active class as the file name for SharedPreferences
    3. PreferenceManagerIn the classgetDefaultSharedPreferences()methods
      • A static method
      • To receive aContextparameter
      • Automatically prefix the package name of the current applicationSharedPreferencesfile
  • Store data in the SharedPreferences file
    1. callSharedPreferencesThe object’sedit()Method to obtain aSharedPreferences.Editorobject
    2. toSharedPreferences.EditorObject to add data to

      (Add Boolean putBool(), add string putString() etc.)
    3. callapply()Method to commit the added data
    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
    editor.putString("name", "Tom");
    editor.putInt("age", 29);
    editor.putBoolean("married", false);
    editor.apply();
    Copy the code
  • Read data from the SharedPreferences file
    • The SharedPreferences object provides a series ofgetMethod, each corresponding to one of the SharedPreferences.EditorputMethods (E.g. getBoolean(), getString())
    • thesegetThe method takes two parameters
      • The first parameter is the key
      • The second argument is the default value returned when no corresponding value is found for the passed key
    SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
    String name = pref.getString("name", "");
    int age = pref.getInt("age", 0);
    boolean married = pref.getBoolean("married", false);
    Copy the code

SQLite database storage

  • Lightweight relational database
  • Supports standard SQL syntax and follows ACID transactions of the database

Creating a database

  • SQLiteOpenHelperHelper classes
    • An abstract class
    • Two abstract methodsonCreate()andonUpgrade()Create and upgrade database logic
    • Both instance methods can open or create (/ upgrade) an existing database, except when the database cannot be written
      • getReadableDatabase()The returned object is opened read-only
      • getWritableDatabase()An exception will occur
    • Two constructors can be overridden, usually using a constructor with fewer parameters
      • The constructor takes four parameters
      • The first argument is Context
      • The second parameter is the database name
      • The fourth parameter represents the version number of the current database and can be used to upgrade the database
    • buildSQLiteOpenHelperInstance, and then call itsgetReadableDatabase()orgetWritableDatabase()You can create a database;

      Database file storage/data/data/<package name>/databases/Directory;

      Rewritten at this pointonCreate()Methods are also executed (not when the database already exists)
    public class MyDatabaseHelper extends SQLiteOpenHelper {
        public static final String CREATE_BOOK = "create table Book ("
                + "id integer primary key autoincrement, "
                + "author text, "
                + "price real, "
                + "pages integer, "
                + "name text)";
    
        private Context mContext;
    
        public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
            mContext = context;
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_BOOK);
            Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public  void  onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    Copy the code

Use ADB shell to view the database

  • The debugging tool delivered with the Android SDK is stored in the platform-tools directory of the SDK

    (Generally, on WindowsC:\Users\<user name>\AppData\Local\Android\Sdk\platform-tools)

    Configure the adb path to the environment variable
  • Open the command line and enteradb shellEnter the console of your Android device
  • cd /data/data/<package name>/databases/Go to the directory where the database files are stored

    lsView the files in this directory
    • Two database files:

      BookStore.dbIt’s the database file we created

      BookStore.db-journalIs a temporary log file (typically 0 bytes in size) that is created to enable the database to support transactions
  • sqlite3 <database name>Open the database

    .tableSee which tables are in the database (android_metadataTables are automatically generated in every database.

    .schemaView building statements

    .exitor.quitExiting the database
  • Query:select * from Book

Upgrading a Database

  • Update database:onUpgrade()
  • How to performonUpgrade(): Pass a higher version number in the constructor of SQLiteOpenHelper
    dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
    Copy the code

Add data

  • With the help ofgetReadableDatabase()orgetWritableDatabase()The returnedSQLiteDatabseThe object ofCRUDoperation
  • SQLiteDatabseprovidesinsert()methods
  • Accepts three parameters

    The first parameter is the name of the table to which the data is to be added

    The second argument is used to automatically assign NULL to some nullable columns without specifying to add data, usually passed directlynullCan be

    The third parameter is aContentValuesObject, which provides a series ofput(), used toContentValuesTo add data, pass in the name of each column in the table and the corresponding data to add
    SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "The Da Vinci Code"); values.put("author", "Dan Brown"); values.put("pages", 454); Values. The put (" price ", 16.96); db.insert("Book", null, values); values.clear(); values.put("name", "The Lost Symbol"); values.put("author", "Dan Brown"); values.put("pages", 510); Values. The put (" price ", 19.95); db.insert("Book", null, values);Copy the code

Update the data

  • SQLiteDatabseprovidesupdate()methods
  • Receive four parameters

    The first parameter is the table name

    The second parameter isContentValuesobject

    The third and fourth parameters constrain the update of a row or rows. If they are not specified, all rows are updated by default
    • The third row corresponds to the SQLwherePart, which updates all names equal to? The rows of

      ?Is a placeholder that can be specified for each placeholder in the third through an array of strings provided by the fourth argument
    SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); Values. The put (" price ", "10.99"); db.update("Book", values, "name = ?" , new String[] { "The Da Vinci Vode" });Copy the code

Delete the data

  • SQLiteDatabseprovidesupdate()methods
  • Accepts three parameters

    The first parameter indicates that the second and third parameters are used to restrict the deletion of one or more rows. If this parameter is not specified, all rows are deleted by default
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    db.delete("Book", "page > ?", new String[] { "500" });
    Copy the code

Query data

  • SQLiteDatabse provides the query() method

  • The shortest method overloading also requires passing in seven parameters

    • The first parameter is the table name
    • The second parameter is used to specify which columns to query, or default to query all columns
    • The third and fourth parameters constrain the query of a row or rows. If this parameter is not specified, all rows are queried by default
    • The fifth parameter is used to specify the columns that need to be group by. If this parameter is not specified, the query result will not be group by
    • The sixth parameter is used to further filter the data after group by. If this parameter is not specified, no filtering is performed
    • The seventh parameter specifies the sorting method of the query results. If this parameter is not specified, the default sorting method is used
    Query () method parameter Corresponding SQL section describe
    table from table_name Specifies the table name for the query
    columns select column1, column2 Specifies the column name for the query
    selection where column = value Specify constraints on where
    selectionArgs Provide specific values for placeholders in where
    groupBy group by column Specify the columns that need group by
    having having column = value Further constrain the result after group by
    orderBy order by column1, column2 Specifies how to sort the query results
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor = db.query("Book", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String author = cursor.getString(cursor.getColumnIndex("author"));
            int pages = cursor.getInt(cursor.getColumnIndex("pages"));
            double price = cursor.getDouble(cursor.getColumnIndex("price"));
        } while (cursor.moveToNext());
    }
    cursor.close();
    Copy the code

Use SQL to operate the database

  • Add data
    db.execSQL("insert into Book (name, author, page, price) values(? ,? ,? ,?) ", new String[] {"The Da Vinci Code", "Dan Brown", "454", "16.96"}); db.execSQL("insert into Book (name, author, page, price) values(? ,? ,? ,?) ", new String[] {"The Lost Symbol", "Dan Brown", "510", "19.95"});Copy the code
  • Update the data
    db.execSQL("update Book set price = ? where name = ?" , new String[] {"10.99", "The Da Vinci Code"});Copy the code
  • Delete the data
    db.execSQL("delete from Book where page > ?" , new String[] { "500" });Copy the code
  • Query data
    db.rawQuery("select * from Book", null);
    Copy the code

Use LitePal to manipulate the database

  • LitePal is an open source Android database framework that encapsulates some common database functions using object Relational Mapping (ORM).

Configuration LitePal

  • Most open source projects commit to JCenter by declaring a reference to the open source library in the app/build.gradle file
  • Edit the app/build.gradle file and add to the dependencies closure:
    The compile 'org. Litepal. Android: core: 1.3.2'Copy the code
  • Configure the litepal. XML file. Create a folder in app.src.main, create an assets directory, and create the litepal
    <? The XML version = "1.0" encoding = "utf-8"? > <litepal> <dbname value="BookStore" ></dbname> <version value="1" ></version> <list> </list> </litepal>Copy the code
    • <dbname>Specify the database name,<version>Specify the database version number,<list>Specify all mapping models
  • Configure androidmanifest.xml to add attributes to tags

    android:name="org.litepal.LitePalApplication"

Create and upgrade the database

  • Declare a Java class that corresponds to a table in the database. Each field in the class corresponds to each column in the table, and each field generates the corresponding getter and setter methods
  • To add a Java class to the mapping model type table, modify litepal.xml:
    <list>
        <mapping class="<package name>.<class name>"></mapping>
    </list>
    Copy the code
  • Any database operation is performed, and the database for the class is created automatically

    E.g. Connector.getDatabase()(Automatically generates table_SCHEMA tables for LitePal internal use)
  • Update: Modify the contents of the class and increment the version number by 1 (no need to drop the previous table)
  • For CRUD operations, model classes need to inherit fromDataSupport

Add data

  • Create an instance of the model class, set up all the data you want to store, and call the save() method

Update data:

  1. Reset the value of the stored object and call the save() method again
    • model.isSave(): Indicates whether the object has been stored
    • Model.save () has been called to add data

      Or when the Model object is queried through the query API provided by LitePal

      model.isSave()Returns true
  2. Create a new instance, use setters to set values to update, and call the instance’supdateAll()methods
    Book book = new Book(); Book. SetPrice (14.95); book.setPress("Anchor"): book.updateAll("name = ? and author = ?" , "The Lost Symbol", "Dan Brown");Copy the code
    • You can specify a constraint or update all data if you don’t
    • Setters cannot be set to default values, and LitePal will not update updateAll() that is set directly to default values using setters
  • setToDefault(): Sets the default value
    Book book = new Book();
    book.setToDefault("pages");
    book.updateAll();
    Copy the code

Delete the data

  1. Of a direct call to a stored objectdelete()methods
  2. DataSupport.deleteAll()

    The first parameter specifies that the data in that table should be deleted

    The following parameters are used to specify constraints
    DataSupport.deletaAll(Book.class, "price < ?", "15");
    Copy the code
    • If no constraint is specified, all data in the table is deleted by default

Query data

  • Query all data in the table
    List<Book> books = DataSupport.findAll(Book.class);
    Copy the code
  • Query the first data in the table
    Book firstBook = DataSupport.findFirst(Book.class);
    Copy the code
  • Query the last data in the table
    Book LastBook = DataSupport.findLast(Book.class);
    Copy the code
  • Contiguous query:
    • select()Used to specify which columns of data to query
      List<Book> books = DataSupport.select("name", "author").find(Book.class);
      Copy the code
    • where()Used to specify constraints on the query
      List<Book> books = DataSupport.where("pages > ?" , "400").find(Book.class);Copy the code
    • order()Used to specify how the results are sorted
      List<Book> books = DataSupport.order("price desc").find(Book.class);
      Copy the code
      • Desc indicates descending order, and ASC or no writing indicates ascending order
    • limit()Only look up the first three pieces of data in the table
      List<Book> books = DataSupport.limit(3).find(Book.class);
      Copy the code
    • offset()The offset used to specify the result of the query E.g. queries items 2-4 in the table
      List<Book> books = DataSupport.limit(3).offset(1).find(Book.class);
      Copy the code
    • Any combination of links
  • callDataSupport.findBySQL()Do native SQL queries

    The first parameter specifies the SQL statement, and the following parameter specifies the placeholder value

    Return a Cursor object
    Cursor c = DataSupport.findBySQL("select * from Book where pages > ? and price < ?" 20 ", "400", ");Copy the code