Android: Creating SQLite databases and creating databases on SD cards (2)

Source: Internet
Author: User

From: http://blog.csdn.net/chthq/article/details/7838033

2. Create a database on the SD card

Through the sqliteopenhelper class source code of Android, you can see the getwritabledatabase of the sqliteopenhelper class

This interface actually calls the openorcreatedatabase method of context, which does not support database names with paths.

That is to say, the database created using this method can only be stored in the/data/package name/directory; To create a database on the SD card

You can call the openorcreatedatabase method of the sqlitedatabase class. This method supports database names with paths.

The following question is how to determine whether an SD card exists and how to obtain the path of the SD card?

Determine whether an SD card exists:

Android. OS. environment. media_mounted.equals (

Android. OS. environment. getexternalstoragestate ());

Obtain the SD card path: String dbpath = Android. OS. environment. getexternalstoragedirectory ()

. Getabsolutepath ();

To create a database on an SD card, follow these steps:

String dbpath = Android. OS. environment. getexternalstoragedirectory ()

. Getabsolutepath () + "/Database ";
File DBP = new file (dbpath );
File DBF = new file (dbpath + "/" + "test. DB ");


If (! DBP. exists ()){
DBP. mkdir ();
}

// Whether the database file is successfully created
Boolean isfilecreatesuccess = false;

If (! DBF. exists ()){
Try {
Isfilecreatesuccess = DBF. createnewfile ();
}
Catch (ioexception ioex ){

}

}
Else {

Isfilecreatesuccess = true;
}
If (isfilecreatesuccess)
DB = sqlitedatabase. openorcreatedatabase (DBF, mfactory );


For convenience, we can use the above method to override the getwritabledatabase method of the sqliteopenhelper class,

For other logics, refer to the sqliteopenhelper class. Finally, do not forget to add the read and write permissions of the SD card:

<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.