Android provides five ways for users to save persistent application data. Make choices according to your own needs, such as whether the data is private to the application, whether it can be accessed by other programs, and how much data storage space is required, respectively:
- File storage data
- Using SharedPreferences to store data
- SQLite database stores data
- Use ContentProvider to store data
- Network storage data
A file stores data
1.1 operation mode of Android files
1.2 operation methods related to documents
1.3 document reading and writing
File reading and writing in Android is the same as file I/O in Java, and the process is also very simple. Let's write a simple example below:
write file
public void save(){ String data = "save something here"; FileOutputStream out = null; ButteredWriter writer = null; try{ out = openFileOutput("data",Context.MODE_PRIVATE); writer = new ButteredWriter(new OutputSreamWriter(out)); writer.write(data); }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(writer!=null){ writer.close(); } }catch(IOException e){ e.printStackTrace(); } }
Read data
public String load(){ FileInputStream in = null; ButteredReader reader = null; StringBuilder builder = new StringBuilder(); try{ in = openFileInput("data"); reader = new ButteredReader(new InputStreamReader(in)); String line= ""; while((line = reader.readline()) != null){ builder.append(); } }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try{ reader.close(); }catch(IOException e){ e.printStackTrace(); } } } }
Second, SharedPreferences stores data
2.1 use process
2.2 use examples
Store data
Call the edit() method of the SharedPreferences object to get a SharedPreferences Editor object
Add data putBoolean, putString, and so on to the Editor object
Call the commit() method to submit data
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit(); editor.putString("name","ZhangSan"); editor.putInt("age",12); editor.putBoolean("isMarried",false); editor.commit();
Read data from SharedPreferences file
SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE); String name = pref.getString("name"); int age = pref.getInt("age"); boolean isMarried = pref.getBoolean("isMarried");
III. data stored in SQLite database
Sqlite introduction:
Sqlite database is a lightweight database. It has the advantages of cross platform and multi language operation. It is widely used in small web application systems including browser, IOS, Android and some portable requirements. It has the advantages of low resource occupation and fast processing speed.
3.1 basic concepts of SQLite
① SQLite is a lightweight relational database with fast operation speed and less resources. It is very suitable for use on mobile devices. It not only supports standard SQL syntax, but also follows the acid (database transaction) principle. It does not need an account and is very convenient to use!
② Previously, we learned to use files and SharedPreference s to save data, but in many cases, files are not necessarily effective. For example, multithreading concurrent access is related; app has to deal with complex data structures that may change, and so on! Such as bank deposit and withdrawal! Using the first two will be very weak or cumbersome. The emergence of database can solve this problem, and Android provides us with such a lightweight SQLite. Why not?
③ SQLite supports five data types: null, Integer, real (floating point number), text (string text) and blob (binary object). Although there are only five data types, varchar,char and other data types can be saved; Because SQLite has a biggest feature: you can save data of various data types to any field without caring about the data type declared by the field. For example, you can store strings in fields of Integer type. Of course, fields declared as primary key INTEGER PRIMARY KEY can only store 64 bit integers! In addition, SQLite will ignore the data type information following the field name in the CREATE TABLE statement when parsing the CREATE TABLE statement. For example, the following statement will ignore the type information of the name field: CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))
Several related classes:
Three classes are used when using the database:
SQLiteOpenHelper: abstract class. We can inherit this class and override the methods of database creation and update. We can also obtain database instances through the objects of this class or close the database!
SQLiteDatabase: database access class: we can add, delete, modify and query the database through the objects of this class
Cursor: cursor, which is a bit similar to the resultset and result set in JDBC! It can be simply understood as a pointer to a record in the database!
SQLiteDatabase related methods
execSQL(SQL,Object []): use the SQL statement with placeholder, which is used to execute the SQL statement to modify the database content
rawQuery(SQL,Object []): use the SQL query operation with placeholders. In addition, I forgot to introduce Curosr and related properties. Here I add: -- the Cursor object is somewhat similar to the ResultSet and result set in JDBC! The following methods are provided to move the record pointer of the query result:
move(offset): Specifies the number of rows to move up or down. An integer indicates to move down; Negative numbers move up!
moveToFirst(): the pointer moves to the first row and returns true successfully. It also indicates that there is data
moveToLast(): when the pointer moves to the last position, it returns true successfully;
moveToNext(): the pointer moves to the next line and returns true successfully, indicating that there are still elements!
moveToPrevious(): move to the previous record
getCount() gets the total number of data pieces
isFirst(): is it the first record
isLast(): is it the last item
moveToPosition(int): moves to the specified row
3.2 SQLite usage
1. Insert data:
public void save(Person p) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("INSERT INTO person(name,phone) values(?,?)", new String[]{p.getName(),p.getPhone()}); }
2. Delete data:
public void delete(Integer id) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("DELETE FROM person WHERE personid = ?", new String[]{id}); }
3. Modify data:
public void update(Person p) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("UPDATE person SET name = ?,phone = ? WHERE personid = ?", new String[]{p.getName(),p.getPhone(),p.getId()}); }
4. Query data:
public Person find(Integer id) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM person WHERE personid = ?", new String[]{id.toString()}); //true is returned only when there is data if(cursor.moveToFirst()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); return new Person(personid,name,phone); } cursor.close(); return null; }
5. Data paging:
public List<Person> getScrollData(int offset,int maxResult) { List<Person> person = new ArrayList<Person>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM person ORDER BY personid ASC LIMIT= ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)}); while(cursor.moveToNext()) { int personid = cursor.getInt(cursor.getColumnIndex("personid")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); person.add(new Person(personid,name,phone)) ; } cursor.close(); return person; }
6. Number of query records:
public long getCount() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT COUNT (*) FROM person",null); cursor.moveToFirst(); long result = cursor.getLong(0); cursor.close(); return result; }
IV. data stored by ContentProvider
4.1 related concepts
A data storage method that can be shared by all applications in Android system. Because data is usually private among applications, this storage method is rarely used, but it is an essential storage method. For example, audio, video, pictures and address books can generally be stored in this way. Each ContentProvider will provide a public URI (wrapped as a URI object) to the outside. If the application has data to share, it needs to use the ContentProvider to define a URI for these data, and then other applications will pass in the URI through the Content Provider to operate the data.
A program can completely expose its own data by implementing an abstract interface of ContentProvider, and ContentProviders expose the data in a way similar to the table in the database, that is, ContentProvider is like a "database". Then the operation of obtaining the data provided by the outside world should be basically the same as that of obtaining the data from the database, except that the URI is used to represent the "database" that the outside world needs to access.
4.1 use related
1. Define a class that inherits from the ContentProvider base class.
The following methods are implemented:
onCreate(): called after the ContentProvider is created.
insert(): inserts data corresponding to values according to Uri.
delete(): deletes all records matching the selection criteria according to the Uri.
update(): modify all records matching the selection criteria according to the Uri.
query(): query all records matching the selection criteria according to the Uri. projection is a list of column names indicating that only the specified data column is selected.
getType(): returns the MIME type of the data represented by the current Uri.
At androidmanifest When registering a custom ContentProvider class in XML, you also need to specify the authorities attribute, that is, Uri.
2. What is URI?
Uri represents the absolute path of the data table to be operated. It mainly contains two parts of information:
ContentProvider requiring action
Operate on the table in the ContentProvider.
A Uri consists of the following parts:
- schema: Android fixed set to content://
- Authority: used to uniquely identify this ContentProvider. External callers can find it based on this identification.
- path: the database table to operate on.
- id: optional field, used to operate a specific data item.
3.ContentResolver operation data
The function of ContentProvider is to expose the data available for operation. Other applications operate the data exposed by ContentProvider through ContentResolver.
First, get the ContentResolver object:
getContentResolver(): get and apply the default ContentResolver.
Next, manipulate the data through the ContentResolver object:
insert(): insert the data corresponding to values into the ContentProvider corresponding to Uri.
delete(): deletes the data matching the selection condition in the ContentProvider corresponding to the Uri.
update(): updates the data matching the selection condition in the ContentProvider corresponding to the Uri.
query(): query the data matched by the selection condition in the ContentProvider corresponding to the Uri.
V. network storage data
Network storage: it stores / obtains data information through the storage space provided by the network.