1 Use SharedPreferences to store data.
2 file storage data
3 SQLite database stores data
4 Use ContentProvider to store data
5 network storage data
Different business logic or requirements are implemented in different ways. The following are the explanations and methods of these data storage methods:
First, use SharedPreferences to store data.
SharedPreferences is a lightweight storage class on the Android platform, which mainly stores some common configurations such as window state.
In general, the window state onSaveInstanceState is overloaded in the activity, and is generally saved by using SharedPreferences.
It provides traditional long integer, integer and string storage for cloning on Android platform.
SharedPreferences is similar to the ini configuration file on Windows system in the past, but it is divided into multiple permissions.
Global * * *, android 123 prompts can be saved in xml, and the overall efficiency is not particularly high.
It is much better than SQLite for traditional lightweight. If the storage capacity is really small, you can consider defining your own file format.
When dealing with xml, Dalvik will parse it through its own local XML parser, such as XMLpull, which is better for memory resources.
Its essence is to store key-value pair data based on XML file, which is usually used to store some simple configuration information.
Its storage location is /data/data/
SharedPreferences object itself can only obtain data, and does not support storage and modification. Storage modifications are implemented through editor objects.
The steps to implement SharedPreferences storage are as follows:
1. Gets the SharedPreferences object according to the context.
Secondly, use the edit () method to get the editor object.
3. Store key-value pair data through editor objects.
Fourth, submit the data through the commit () method.
Here is the sample code:
Public class MainActivity extends Activity {
@ Overlay
public void on create(Bundle saved instancestate){
super . oncreate(savedInstanceState);
setContentView(r . layout . main);
//Get the SharedPreferences object
Context ctx = MainActivity.this
shared preferences SP = CTX . getsharedpreferences(" SP ",MODE _ PRIVATE);
//store data
editor editor = sp . edit();
editor.putString("STRING_KEY "," STRING ");
editor.putInt("INT_KEY ",0);
Editor.putBoolean("BOOLEAN_KEY ",true);
editor . commit();
//Returns the value of STRING_KEY.
Log.d("SP ",sp.getString("STRING_KEY "," none "));
//If NOT_EXIST does not exist, the return value is "None".
Log.d("SP ",sp.getString("NOT_EXIST "," none "));
}
}
After executing this code, an SP.xml file will be generated in the directory of/data/data/com.test/shared _ prefs, and an application can create multiple such xml files.
Compared with SQLite database, SharedPreferences object is more convenient and concise, which saves many operations such as creating database, creating tables and writing SQL statements.
However, SharedPreferences also has its own shortcomings, such as its function of storing five simple data types: boolean, int, float, long and String, such as its inability to make conditional queries.
Therefore, the data storage operation of SharedPreferences, no matter how simple, can only be a supplement to the storage method, and cannot completely replace other data storage methods such as SQLite database.
The second type: file stores data.
As for file storage, Activity provides the openFileOutput () method, which can be used to output data to a file. The specific implementation process is the same as saving data to a file in J2SE environment.
Files can be used to store a large amount of data, such as text, pictures, audio and so on.
Default location: /data/data/
Code example:
Public void save(){
Try {
File output stream out stream = this.openfile output ("a.txt", context. Mode _ world _ readable);
outStream.write(text.getText()。 toString()。 getBytes());
out stream . close();
Toast.makeText(MyActivity.this, "save", Toast. Length _ length). show();
} catch(file not found exception e){
Return;
}
catch (IOException e){
Return;
}
}
The first parameter of the openFileOutput () method is used to specify the file name and cannot contain the path delimiter "/". If the file does not exist, Android will automatically create it.
The created files are saved in the /data/data//files directory, such as/data/data/cn.itcast.action/files/itcast.txt,
Click Eclipse menu window-Show View-Other to expand the android folder in the dialog window.
Select the file explorer view below, and then expand the /data/data//files directory in the file explorer view to view the file.
The second parameter of the openFileOutput () method is used to specify the operation mode. There are four modes, namely:
Context. MODE_PRIVATE = 0
Context. MODE_APPEND = 32768
Context. MODE_WORLD_READABLE = 1
Context. MODE_WORLD_WRITEABLE = 2
Context. MODE_PRIVATE: is the default operation mode, which means that the file is private data and can only be accessed by the application itself. In this mode, the content written will overwrite the content of the original file. If you want to append the newly written content to the original file. You can use context. Mode _ Append.
Context. MODE_APPEND: mode checks whether the file exists, and if it exists, it will append the content to the file, otherwise it will create a new file.
Context. Mode _ World _ Readability and Context. Mode _ world _ writable is used to control whether other applications have permission to read and write the file.
MODE_WORLD_READABLE: indicates that the current file can be read by other applications;
Mode _ world _ writable: indicates that the current file can be written by other applications.
If you want the file to be read and written by other applications, you can pass in: openfile output ("itcast.txt ",context.mode _ world _ readable+context.mode _ world _ writable); Android has its own security model. When an application (. Apk), the system will assign it a user id. When an application wants to access other resources such as files, it needs userid matching. By default, files created by any application, sharedpreferences and database should be private (located in /data/data//files) and other programs cannot access them.
Unless you specify a context. Mode _ World _ Readable or Context. Mode _ world _ writable When you create it, only in this way can other programs access it correctly.
Example of reading a file:
Public void load(){
Try {
file inputstream inStream = this . openfile input(" a . txt ");
ByteArrayOutputStream = new ByteArrayOutputStream();
Byte[]buffer = new byte [1024];
int length =- 1;
while((length = instream . read(buffer))! =- 1) {
Stream.write (buffer, 0, length);
}
stream . close();
instream . close();
text . settext(stream . tostring());
Toast.makeText(MyActivity.this, "loaded", Toast. Length _ length). show();
} catch(file not found exception e){
e . printstacktrace();
}
catch (IOException e){
Return;
}
}
A private file can only be accessed by the application that created it.
If you want other applications to read and write the file,
You can specify the context. MODE_WORLD_READABLE and context.mode _ world _ writable permissions when creating files.
Activity also provides getCacheDir () and getFilesDir () methods: g.
The etCacheDir () method is used to get the /data/data// cache directory, and the getFilesDir () method is used to get the /data/data//files directory.
Save the file in SDCard:
Use the openFileOutput () method of Activity to save the file, which is stored in the mobile phone space.
Generally, the storage space of mobile phones is not very large, so it is ok to store some small files, but it is not feasible to store large files like videos.
For large files like video, we can store them in SDCard.
What does SDCard do? You can think of it as a mobile hard disk or a USB flash drive.
To use SDCard in the simulator, you need to create an SDCard first (of course, it is not a real SDCard, just a mirror file).
Creating SDCard can be done when Eclipse creates the simulator, or it can be done by using DOS command.
As follows: enter the tool directory of android SDK installation path in Dos window,
Enter the following command to create an SDCard with a capacity of 2G, and the file suffix can be taken at will.
It is recommended to use. Img: mkSD card 2048m d: \ androidtool \ sdcard.img access sdcard in the program. You need to apply for access to SDCard.
Add access to SDCard in AndroidManifest.xml, as shown below:
& lt! -Permission to create and delete files in SDCard->
& ltuses-permission Android:name = " Android . permission . mount _ UNMOUNT _ file systems "/& gt;
& lt! -permission to write data to SDCard->
& ltuses-permission Android:name = " Android . permission . write _ EXTERNAL _ STORAGE "/& gt;
To store files in SDCard, the program must first determine whether the mobile phone is equipped with SDCard and can read and write.
Note: To access SDCard, you must add the right to access SDCard in AndroidManifest.xml
if(environment . getexternalsragestate()。 Equal to (environment. MEDIA_MOUNTED)){
file sdCardDir = environment . getexternalstrauredirectory(); //get the SDCard directory
File saveFile = new File(sdCardDir," a . txt ");
file output stream out stream = new file output stream(save file);
outStream.write("test "。 getBytes());
out stream . close();
}
Environmental methods. GetExternalStorageState () is used to get the status of SDCard. If the mobile phone is equipped with SDCard and can read and write, the state returned by this method is equal to the environment. Media installation.
Environmental methods. GetExternalStorageDirectory () is used to get the directory of SDCard. Of course, to get the directory of SDCard, you can also write:
File sdCardDir = new file ("/SD card"); //get the SDCard directory
File saveFile = new File(sdCardDir," it cast . txt ");
//The above two codes can be combined into one sentence:
File save File = new File("/SD card/a . txt ");
file output stream out stream = new file output stream(save file);
outStream.write("test "。 getBytes());
out stream . close();
The third type: SQLite database stores data
SQLite is a lightweight embedded database engine that supports SQL language.
And it only needs a little memory to have good performance.
In addition, it is open source and anyone can use it.
Many open source projects (Mozilla, PHP, Python) use SQLite.
SQLite consists of the following components: SQL compiler, kernel, backend and accessories.
By using virtual machine and virtual database engine (VDBE), SQLite makes it more convenient to debug, modify and extend the SQLite kernel.
Features:
For devices with limited resources,
If there is no server process,
All data are stored in the same file, which is cross-platform,
Can be copied freely.
SQLite basically conforms to the SQL-92 standard and is no different from other mainstream SQL databases. Its advantage is high efficiency, and the Android runtime environment contains a complete SQLite.
The biggest difference between SQLite and other databases is the support for data types. When you create a table, you can specify the data type of the column in the CREATE TABLE statement, but you can put any data type in any column. When a value is inserted into the database, SQLite will check its type. If the type does not match the associated column, SQLite will try to convert the value to the type of the column. If it cannot be converted, the value will be stored as its own type. For example, you can put a string in an integer column. SQLite calls it "list typing". In addition, SQLite does not support some standard SQL functions, especially foreign key constraints, nested transcaction, right join and outer joins, and some ALTER TABLE functions. In addition to the above functions, SQLite is a complete SQL system with complete triggers, transactions and so on.
Android integrates SQLite database. Android integrates SQLite at runtime, so every Android application can use SQLite database.
For developers who are familiar with SQL, using SQLite in Android development is quite simple. But JDBC will consume too many system resources, so JDBC is not suitable for mobile phones with limited memory. Therefore, Android provides some new APIs to use SQLite database, and programmers need to learn to use these APIs in Android development.
Databases are stored in data/ /databases/. Using SQLite database activities in Android development can access the database through content providers or services.
The following will explain in detail how to create a database, add data and query the database. Creating a database Android does not automatically provide a database. To use SQLite in Android applications, you must create your own database, and then create tables, indexes and data.
Android provides SQLiteOpenHelper to help you create a database. By inheriting the SQLiteOpenHelper class, you can easily create a database. The SQLiteOpenHelper class encapsulates the logic for creating and updating databases according to the needs of developing applications.
Subclasses of SQLiteOpenHelper need to implement at least three methods:
1 constructor, calling the constructor of the parent class SQLiteOpenHelper. This method requires four parameters: the context (for example, an activity), the database name, an optional cursor factory (usually Null), and an integer representing the version of the database model used.
2 onCreate () method, which requires a SQLiteDatabase object as a parameter, and fills the table and initializes the data for the object as needed.
3 onUpgrage () method, this method needs three parameters, a SQLiteDatabase object, an old version number and a new version number, so that you can know how to change a database from the old model to the new model.
The fourth method of using ContentProvider to store data, ContentProvider actually stores data through a database, so I won't describe it in detail here.
The fifth network stores data, which means that the data is stored in the server. On android, you only need to send a request through httpclient to get data from the server.