How to save the database to SD card based on Android

Sometimes the database will be saved to external storage or SD card (in this case, data can be encrypted to avoid data cracking). For example, when an application supports multiple data, each data needs to have a corresponding database, and the amount of information in the database is particularly large, it is obviously more important to save the database in external storage or SD card, Because the size of ram is limited; Secondly, when writing some test programs, it is more convenient to save the database on the SD card to view the contents of the database.

When Android creates a database through sqliteopenhelper, the database is saved in the '/ data / data / application name / databases' directory by default. You only need to pass in the database name in the constructor inheriting sqliteopenhelper class. However, if you save the database under the specified path, you need to rewrite the context in the constructor inheriting sqliteopenhelper class, Because: when reading the source code of sqliteopenhelper.java, you will find that database creation is realized through the openorcreatedatabase method of context. If we need to create a database under the specified path, we need to write a class to inherit the context, copy its openorcreatedatabase method, and specify the path of database storage in the openorcreatedatabase method, The following is the source code of getwritabledatabase and getreadabledatabase methods in sqliteopenhelper. Sqliteopenhelper uses these two methods to create databases.

Through the above analysis, you can write a custom context class that inherits the context. However, since there are other abstract functions in the context other than the openorcreatedatabase method, it is recommended to use the non abstract class contextwrapper, which inherits from the context. The source code of the self-defined databasecontext class is as follows:

In the constructor that inherits the subclass of sqliteopenhelper, replace the context with an instance of databasecontext:

How to save the database to the SD card based on Android is so much for you. At the same time, thank you very much for your support for the programming tips website. Thank you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>