In this day and age, data is becoming increasingly important, not only for countries, but also for individuals and companies. But the volume of data is so large that it is a problem to deal with it. Today we’ll take a look at how Android solves it.

There are three main ways to store data in Android:

  • File storage
  • SharedPreferences storage
  • SQLite database storage

Before introducing each of these methods, it is important to know where the data files are stored by default for subsequent verification

1 File File storage

The Context class provides the openFileInput() and openFileOutput() methods to open the IO stream of files in the database.

Add an instance of EditText to the layout, and then override onDestroy() to save the input text before the activity is destroyed. This is mainly done through the openFileOutput() method to store the obtained data in the data file. It gets a FileOutputStream, builds an OutputStramWriter from it, and then builds a BufferedWriter from OutputStreamWriter, At this point, you can write the text to the file.

Key part code:

FileOutputStream fileOutputStream = openFileOutput("data", Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(text);
Copy the code

Here are two arguments to openFileOutput(). The first, needless to say, represents the file name. Where to store the data. The second is the mode of operation of the file:

It is recommended to use private or write 0 directly, which has the same meaning.

(2) Read data

In OnCreate(), the openFileInput() method specifies that data is to be read from the file data, after which the code and write correspond very well.

Key code:

FileOutputStream fileOutputStream = openFileOutput("data", Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(text);
Copy the code

2. SharePreferences storage

SharePreferences is a lightweight data storage method that is commonly used to store simple configuration information such as INT, String, Boolean, float, and LONG. Its essence is to store key-value pair data based on XML files.

The steps to implement SharedPreference storage are as follows:

(1) Call getSharedPreferences() to get the SharedPreferences object, which provides two parameters, specifying the file name and the mode of operation.

(2) Call the Edit () method of the SharedPreferences object to get the SharedPreferences.Editor reference object

(3) Call the putXXX() method of the Edit interface to save data of type XXX as key-value pairs.

(4) Call the Commit () method of the Edit interface to commit the key-value pair

Be sure to use the Editor object instead of the SharedPreferences object to store or modify data. But getting the data requires calling the getXXX() method of the SharedPreferences object.

There are many other methods we need to explore, use the same method, change the type is OK.

3.SQLite database storage

SQLite is a lightweight relational database. It is very fast and consumes very few resources. It can be used to store a large number of complex relational data, which is much better than the previous two storage methods for simple data.

(1) Create a database

Start with a class called SQLiteOpenHelper, which is a helper class for SQLiteDatabase that manages database creation and upgrades. SQLiteOpenHelper SQLiteOpenHelper

First: customize the helper class and inherit SQLiteOpenHelper, and rewrite two methods: onCreate() and onUpgrade(), respectively, to implement the logic of creating and upgrading the database in these two methods. You also need a constructor, which in this case takes four parameters.

Step 2: Create database, first instantiate a custom help class, and provide four parameters, meaning (context, database name, create Cursor factory class, version number). Step 3: Use the getReadableDatabase() and getWritableDatabase() helper objects to create or open an existing database (if the database already exists, create a new database otherwise) and return a SQLiteDatabase that can be used for the database. The fourth step: then you can use the database to add, delete, change and check the operation.

Start with the custom helper class and rewrite the two methods and constructors. Here, use the help class to help create a student table containing the student id, name, age, and grade, with the corresponding SQL statement in a string constant. Note that the statement must be accurate, multiple Spaces will fail to build a table. The onCreate() method returns an SQLiteDatabase object, and I finally get to the first common method for SQLiteDatabase, execSQL(), which is versatile enough to accept and process SQL statements. In other words, The add, delete, change, and query methods that you’ll learn later can be used not only to provide a good ready-to-use auxiliary method, but also to call execSQL() directly from a native SQL statement. The former method will be covered in the rest of this tutorial. ExecSQL () is called here to create the table and print a line of the Toast.

Basic code for creating a database:

You can add your own layout and button click listening events. I’m just implementing it directly here, not dealing with any logic.

(2) Increase data

Now look at the ContentValues class you saw earlier, which uses its PUT () method to store primitive type data as key-value pairs. It’s used in addition and modification, so keys are the names of the properties in the table, and values are the data in the table. The common method clear() is also used to clear all data.

Insert () is the auxiliary method used to add data to SQLiteDatabase. The three parameters are the name of the table being operated on, the name of the null-valued field, and the data is the ContentValues object. The second parameter is usually passed null. Insert two rows from student (id = 0); insert two rows from student (id = 0);

(3) Delete data

The auxiliary method for deleting data is delete(), where the first parameter again represents the table name and the second and third parameters constrain the deletion of a row or rows. Select * from student where age > 17;

(4) Change the data

The update() method provides four parameters, (table name, ContentValues object, constraint, constraint), which we learned before! Let’s change Lucy’s grade to senior three.

(5) Query data

The query method quary() is more complex and requires at least seven arguments (table, columns, Selection, selectionArgs, groupBy, Having, orderBy). Table name, column name to be queried, query clause, placeholder value corresponding to selection statement, column name to be grouped, post-grouping filter criteria, sorting method) Don’t worry, in most cases a few parameters will do the job. All other parameters are assigned to null.

That’s not all. This method returns a Cursor from which all the data queried is retrieved. MoveToFirst () moves the pointer to the first row of the result set; GetColumnIndex () retrieves the index of a column at the corresponding position in the table; Get something () passes in an index to get some type of data at the corresponding location; Close () closes the pointer.

(6) Upgrade the database

The second method onUpdate() in MyHelper needs to be overridden to help the database with version updates. For example, if you need to add a new course table to the database, just write the course creation operation in update() and make it called. Remember that the fourth argument version number is passed in to instantiate the help class? Update () can be performed by passing a number greater than 1. In the code below, oldVersion is used to determine the oldVersion number. If it is 1, you just need to create the course table again. If you run the program for the first time, you just execute onCreate() and the two tables are created together. The advantage of this is that no matter which generation is updated, the previous operational data will not be affected and the current version will be kept up to date.

Modify the code as follows

There are

There is also the onUpgrade method

Action changes in the Activity

In this way, the operation succeeds.

May we be who we really are.