This chapter mainly introduces Android input and output support. Android provides two convenient methods for file IO: openFileOutput and openFileInput. It provides the SharedPreferences tool class for recording and accessing application parameters and options, you can easily read and write Parameter options. In addition, the focus is on the SQLite database and the Android built-in SQLite database, which provides a large number of convenient tools. Finally, gesture support and automatic reading are also special Android input and output .!
[Knowledge point] · SharedPreferences and Editor Introduction: Sometimes, applications need to save a small amount of data, and the format of the data is simple: Common strings, scalar values, etc, for example, various configuration information of the application (such as whether to enable music, whether to use vibrating effects, etc.) and player points), Android provides SharedPreferences for saving such data. SharedPreferences stores data similar to the configuration information format. Therefore, SharedPreferences stores simple key-value pairs. The SharedPreferences interface is mainly used to read the Preferences data of an application. It provides the following common methods to access the key-value Pair: boolean contains (String key) in SharedPreferences ): determine whether SharedPreferences contains data of a specific key.
Abstract Map GetAll (): Get all key-value pairs.
Boolean getXxx (String key, xxx defValue): obtains the value corresponding to the specified key in the SharedPreferences data. If the key does not exist, the default value defValue is returned. Xxx can be boolean, float, int, long, String, and other basic types.
The SharedPreferences interface does not provide the ability to write data. Instead, it uses the internal interface of SharedPreferences to call the edit () method to obtain the corresponding EditZ parameters? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcrbUz/keys/Ct723qM/keys + W/keys + 1xMv509DK/keys + 3aGjxuTW0Hh4eL/keys/ wuLaoa2V5ttTTprXEyv2 + 3c/expires + ye3Kx9K7uPa907/latest + latest/latest + cgqhzbboalqtmbky/latest + latest/latest: java; "> useCount = createPackageContext (" org. lxj. io ", Context. CONTEXT_IGNORE_SECURITY); // where "org. lxj. io is the package name of other programs② Call the getSharedPreferences (String name, int mode) of the Context of other programs to obtain the corresponding SharedPreferences object. ③ If you want to write SharedPreferences of other medical services to the data, call the edit () method of SharedPreferences to obtain the Editor.
· File storage: 1) openFileOutput and openFileInput Context provide the following two methods to open the File IO stream in the data folder of the application:
FileInputStream openFileInput (String name): Open the input stream corresponding to the name file in the data folder of the application. FileOutputStream openOutput (String name, int mode): Open the output stream corresponding to the name file in the data folder of the application. The second parameter specifies the file opening mode:
In addition, Context provides the following methods to access the data folder of an application:
GetDir (String name, int mode): obtain or create a subdirectory corresponding to the name in the data folder of the application. File getFilesDir (): Obtain the absolute path of the data folder of the application. String [] fileList (): returns all files in the data folder of the application. DeleteFile (String): Delete the specified file in the data folder of the application.
2) read and write files on the SD card to better store and retrieve the big file data of the application, the application needs to read and write files on the SD card. The SD card greatly expands the storage capability of mobile phones. Steps for reading and writing SD files: ① call the getExternalStorageState () method of Environment to determine whether the SD card is inserted on the mobile phone, and the application has the permission to read and write the SD card. The following code:
Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED); // If an SD card is inserted and the program has the permission to read and write the SD card, true is returned.
② Call the getExternalStorageDirectory () method of Environment to obtain the external memory, that is, the Directory of the SD card. ③ Use FileInputStream, FileOutputStream, FileReader, or FileWriter to read and write files in the SD card. ④ To have the permission to read and write SD, add the following two configurations to the AndroidAManifest. xml file:
· SQLiteDatabase SQLite is only an embedded database engine. It is applicable to the access to a proper amount of data on devices with limited resources (such as mobile phones and PDAs. SQLite is just a file. Android provides SQLiteDatabase to represent a database (the underlying layer is a database file). Once the application obtains the SQLiteDatabase object representing the specified database, it can manage and operate the database through the SQLiteDatabase object. SQLiteDatabase provides the following static methods to open the database corresponding to a file:
Static SQLiteDatabase openDatabase (String path, SQLiteDatabase. cursorFactory factory, int flags): Open the SQLite database represented by the path file. static SQLiteDatabase openOrCreateDatabase (File file, SQLiteDatabaseCursorFactory factory): Open or create (if not exist) The SQLite database represented by the file File. static SQLiteDatabase openOrCreateDatabase (String path, SQLiteDatabaseCursorFactory factory): Open or create (if not exist) The SQLite database represented by the path file.
After obtaining the SQLiteDatabase object in the program, you can call the following method of SQLiteDatabase to operate the database:
ExecSQL (String SQL, Object [] bindArgs): Execute an SQL statement with a placeholder. ExecSQL (String SQL): Execute an SQL statement. Insert (String table, String nullColumnHack, ContentValues values): insert data to the execution table. Update (String table, ContentValues values, String whereClause, String [] whereArgs): update the specific data in a specific table delete (String table, String whereClause, String [] whereArgs ): deletes specific data from a specified table.
Cursor query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy): queries the executed data table.
Cursor query (String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy, String limit): queries the execution data table. Limit parameter control allows you to query a maximum of several records (used to control paging parameters ).
Cursor query (boolean distinct, String table, String [] columns, String selection, String [] selectionArgs, String groupBy, String having, String orderBy, String limit ): execute a query statement on the specified table. The first parameter controls whether to retrieve duplicate values. RawQuery (String SQL, String [] selectionArgs): executes an SQL query with placeholders. BeginTransaction (): starts a transaction. EndTransaction (): ends a transaction.
The preceding query method returns a Cursor object. Cursor provides the following method to move the record pointer of the query result:
Move (int offset): move the record pointer up or down the specified number of rows. When offset is an integer, it moves down. If offset is a negative number, it moves up boolean moveToFirst (): move the record pointer to the first row. If the record pointer is successfully moved, return trueboolean moveToLast (): Move the record pointer to the last row. If the record pointer is successfully moved, return trueboolean moveToNext (): move the record pointer to the next row. If the record pointer is successfully moved, return trueboolean moveToPosition (int position): Move the record pointer to the specified row. If the record pointer is successfully moved, return trueboolean moveToPrevious (): move the record pointer to the previous row. If the row is successfully moved, true is returned.
Once the record pointer is moved to the specified row, you can call the getXxx () method of Cursor to obtain the data of the specified column in the modified row. · Use SQL statements to operate SQLite databases: execSQL statements of SQLiteDatabase can execute arbitrary SQL statements, including SQL statements with placeholders. However, since this method does not return values, it is generally used to execute DDL statements or DML statements: to execute a query statement, you can call the rawQuery (String SQL, String [] selectionArgs) method of SQLiteDatabase. The sample code is as follows:
Db.exe cSQL ("insert into news_inf values (null ,?,?) ", New String [] {title, content}); // execute the insert statement
Follow these steps to use SQLiteDatabase for database operations: ① obtain the SQLiteDatabase object, which represents the connection to the database. ② Call SQLiteDatabase to execute SQL statements. ③ Operate the execution results of SQL statements, for example, using SimpleCursorAdapter to encapsulate Cursor. ④ Close SQLiteDatabase and Recycle resources. · Transaction: SQLiteDatabase contains two methods to control the transaction: beginTransaction (): Start the transaction. EndTransaction (): ends the transaction. In addition, SQLiteDatabase also provides the following method to determine whether the current context is in the transaction environment. InTransaction (): if the current context is in the transaction, true is returned; otherwise, false is returned. When the program executes the endTransaction () method, the transaction ends-whether the transaction is committed, or roll back the transaction? It depends on whether SQLiteDatabase calls the setTransactionSuccessful () method to set the transaction flag. if the transaction is successfully set when the method is called during execution of the program transaction, the transaction is committed; otherwise, the program will roll back the transaction. Sample Code:
Db. beginTransaction (); // start transaction try {// execute DML statement... // call this method to set transaction success. Otherwise, the endTransaction () method will roll back the transaction db. setTransactionSuccessful ();} finally {// determined by the transaction flag whether to commit the transaction or roll back the transaction db. endTransaction ();}
· SQLiteOpenHelper class: SQLiteOpenHelper is a tool class provided by Android for database management. It can be used to manage database creation and version updates. The general usage is to create a subclass of SQLiteOpenHelper and extend its onCreate (SQLiteDatabase db) and onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) methods. SQLiteOpenHelper includes the following common methods:
Synchronized SQLiteDatabase getReadableDatabase (): Open the SQLiteDatabase object corresponding to the database in read/write mode; SQLiteDatabase getWritableDatabase (): Open the SQLiteDatabase object abstract void onCreate (SQLiteDatabase db) of the database in write mode ): this method is called back when a database is created for the first time. abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion): This method is called back when the database version is updated. synchronized void close (): close all opened sqlitedatabases
Once the SQLiteOpenHelper object is obtained, the program does not need to use the static method of SQLiteDatabase to create the SQLiteDatabase instance, and you can use the getWritableDatabase () or getReadableDatabase () method to obtain a SQLiteDatabase instance used to operate the database.
· Gesture support: Android provides a GestureDetector class. The GestureDetector instance represents a gesture detector. When creating a GestureDetector, You need to input a GestureDetector. the OnGestureDetectorListener instance is a listener that responds to user gestures. Android also allows applications to add user gestures to a specified file, use GestureLibrary to represent the Gesture library, and provide the GestureLibraries tool class to create the Gesture library, providing recognize (Gesture ges) this method returns the ArrayList Prediction encapsulates the gesture matching information. The name attribute of the Prediction object represents the matched gesture name, and the score attribute represents the gesture similarity.
· Automatic reading (TTS): mainly through TextToSpeech. This class provides a constructor: TextToSpeech (Context context, TextToSpeech. after obtaining the TextToSpeech object, you can call the setLanguage (Locale loc) method of TextToSpeech to set the language and country options that the TTS should use. After the TextToSpeech object is used up, you can call the shutdown () method of the Activity to disable TextToSpeech and release the resources it occupies.