Chapter 6 Data Storage

Keywords: Database xml SQLite SQL

I. File Storage
Without any formatting of the stored content, it is suitable for storing simple text data or binary data.
1. Store 5 pieces of music:

  1. Gets the FileOutputStream object, which is obtained through the openFileOutput() method provided by the Context class
  2. Get the OutputStreamWriter object, and pass in the FileOutputStream object obtained above as a parameter
  3. Get the BufferedWriter object whose input parameter is the OutputStreamWriter object obtained above
  4. Write data in BufferedWriter object write() method
  5. Close the BufferedWriter object
   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();
            }
        }
    }

2. Read 5 pieces of music

  1. Get the FileInputStream object
  2. To get the InputStreamReader object, you need to pass in the FileInputStream object obtained above.
  3. To get the BufferedReader object, you need to pass in the InputStreamReader object above.
  4. Read with readLine()
  5. Close the BufferedReader 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();
    }

Shared Preferences Storage
Shared Preferences uses key-value pair to store data
1. Storage of four pieces of music

  1. Three methods for obtaining Shared Preferences objects
    1.1 The getSharedPreferences() method in the Context class, two parameters, name and mode of operation
    1.2 getPreferences() method in Activity class: a parameter, operation mode
    1.3 getDefaultSharedPreferences() method in the PreferenceManager class: a parameter context parameter
  2. Call the edit() method of the SharedPreferences object to get the SharedPreferences.Editor object
  3. Add data, putString(), putBoolean(), etc. to the SharedPreferences.Editor object
  4. Call commit() to write data

2. Read 2 songs

  1. Get the SharedPreferences object
  2. Get data by getString(), getInt(). Two parameters are passed in, one is key and the other is the default value, that is, if the key is not found, the default value is returned.
        saveData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//   1 File name  data.xml
//          SharedPreferences pref = getSharedPreferences("data", Context.MODE_PRIVATE);
//   2  File name MainActivity.xml
//          SharedPreferences pref =  getPreferences(Context.MODE_PRIVATE);
//    3File name is package name.xml
                SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                SharedPreferences.Editor editor = pref.edit();
                editor.putString("name", "Tom");
                editor.putInt("age", 28);
                editor.putBoolean("married", false);
                editor.apply();
                String name = pref.getString("name", "");
                int age = pref.getInt("age", 0);
                boolean married = pref.getBoolean("married", false);
                Log.d("MainActivity", "name is " + name);
                Log.d("MainActivity", "age is " + age);
                Log.d("MainActivity", "married is " + married);

            }
        });

3. SQLite database
1. Creating a database
First, create your own public class MyDatabase Helper extents SQLiteOpenHelper {}
The SQLiteOpenHelper class is an abstract class, rewriting two abstract methods: onCreate() and onUpdate().
You also need to override the construction method. The least parameter construction method has four parameters: Context, database_name, Cursor (generally null, vision version number).
Then, the MyDatabaseHelper object is created and its getReadableDatabase() or getWritableDatabase() method is called.

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,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
        mcontext=context;
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

Called in MainActivity,

databaseHelper = new MyDatabaseHelper(this, "BookStore", null, 1);
databaseHelper.getWritableDatabase();

At this point, a database named BookStore, version 1, is created. Also, the onCreate() method is called to create a table named Book.

2. Upgrade database
Tips
(1) When the same version of the database BookStore already exists, the onCreate() method in MyDatabase Helper will not execute.
(2) If a table is found to exist when it is created, it will report an error directly, so it is necessary to delete the existing table.
(3) The onUpdate() method will only be executed if the version number is higher than the original one.

databaseHelper = new MyDatabaseHelper(this, "BookStore", null, 2);

Add a table in and improve the database version

public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mcontext, "Create Success", Toast.LENGTH_SHORT).show();
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }

Disadvantage: You need to delete existing tables, and previous data will be deleted.
3. Adding data
4. Update data
5. Delete data
6. Query data
7. Operating database directly with SQL
IV. Best practices in Databases
1. Use transactions
First, open the transaction: db.beginTransaction();
Then, the database operation is performed.
Finally, the transaction succeeds: db. setTransaction Successful ();
2. Best Writing Method for Upgrading Database
Before upgrading the database, in order to ensure that the new tables are not available before, it is very unreasonable to delete all tables.
The improvement methods are as follows:
Change version, then make a judgment in onUpdate(), and perform different update operations according to version.

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL(CREATE_CATEGORY);
case 2:
db.execSQL("alter table Book add column category_id integer");
default:
}
}
Edition Changes to the database
version=1 Build database, add table Book 00
version=2 Add table Category
version=3 Add category_id to table Book

If it is the first installation, go directly to onCreate(), and install the latest version directly.
If version 1 is first installed, onUpdate() is entered and upgraded twice in a row.
If version 2 is first installed, onUpdate() is entered and only the last upgrade is made.

Posted by bufo on Tue, 16 Jul 2019 15:05:04 -0700