[Android] How to import existing external databases

Source: Internet
Author: User

the android database operations we usually see are generally to create an empty database at the beginning of the Program , and then perform related operations. What if we need to use an existing database?
we all know that databases in the Android system should be stored in/data/COM. *. * (package name)/directory, so we need to import the existing database to that directory. The operation is to use fileinputstream to read the original database, and then use fileoutputstream to write the read content to that directory.
Operation Method: 1. include the original database in the Res/raw directory of the project source code and create a dbmanager class. The Code is as follows:

Package COM. android. importdatabase; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import android. content. context; import android. database. SQLite. sqlitedatabase; import android. OS. environment; import android. util. log; public class dbmanager {private final int buffer_size = 400000; public static final string DB _ Name = "countries. DB "; // The Name Of The saved database file is public static final string package_name =" com. android. importdatabase "; public static final string db_path ="/Data "+ environment. getdatadirectory (). getabsolutepath () + "/" + package_name; // the location where the database is stored on the mobile phone. Private sqlitedatabase; private context; dbmanager (context) {This. context = context;} public void opendatabase () {This. database = This. opendat Abase (db_path + "/" + db_name);} private sqlitedatabase opendatabase (string dbfile) {try {If (! (New file (dbfile ). exists () {// determines whether the database file exists. If it does not exist, execute import. Otherwise, directly open the database inputstream is = This. context. getresources (). openrawresource (R. raw. countries); // The database fileoutputstream Fos = new fileoutputstream (dbfile); byte [] buffer = new byte [buffer_size]; int COUNT = 0; while (COUNT = is. read (buffer)> 0) {FOS. write (buffer, 0, count);} FOS. close (); is. close ();} sqlitedatabase DB = sqlitedatabase. openorcreatedatabase (dbfile, null); Return dB;} catch (filenotfoundexception e) {log. E ("Database", "file not found"); E. printstacktrace ();} catch (ioexception e) {log. E ("Database", "Io exception"); E. printstacktrace ();} return NULL ;}
// Do something else here
 
Public void closedatabase () {This. database. Close ();}}

Then, in the first activity of the program, an example of a dbmanager object is provided, and then the opendatabase method can be executed to complete the import. You can write some operations to the database in the dbmanager class, then it is called through the dbmanager class object. You can also open the database and perform operations through a sqlitedatabase class object after the import is completed.

My approach is to import the database in the first activity of the program:

 
Package com. Android. importdatabase; import Android. App. Activity; import Android. content. Intent; import Android. OS. Bundle; public class rootview extends activity {public dbmanager dbhelper;
 
@ Overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); dbhelper = new dbmanager (this); dbhelper. opendatabase (); dbhelper. closedatabase ();}}

At this time, we can see in ddms that the external database has been successfully imported

In the class where you need to use the database:

Package COM. android. importdatabase; import Java. util. arraylist; import android. app. activity; import android. database. cursor; import android. database. SQLite. sqlitedatabase; import android. OS. bundle; public class taxiactivity extends activity {private sqlitedatabase database; arraylist <cityclass> city; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentvie W (R. layout. main); database = sqlitedatabase. openorcreatedatabase (dbmanager. db_path + "/" + dbmanager. db_name, null); City = getcity (); // do something with citydatabase. close ();} private arraylist <cityclass> getcity () {cursor cur = database. rawquery ("select city. id_city, city. name from Taxi, city where city. id_city = Taxi. id_city group by city. id_city ", null); If (cur! = NULL) {int num_city = cur. getcount (); arraylist <cityclass> taxicity = new arraylist <cityclass> (num_city); If (cur. movetofirst () {do {string name = cur. getstring (cur. getcolumnindex ("name"); int id = cur. getint (cur. getcolumnindex ("id_city"); cityclass city = new cityclass ("", 0); system. out. println (name); // Add an additional statement to output the SELECT statement to logcatcity. city_name = Name; city. city_id = ID; taxicity. add (city);} while (cur. movetonext ();} return taxicity;} else {return NULL ;}}}

View the output result:

If the size of the imported database is incorrect or the inputstream reading fails, see this post.[IPhone/Android] What should I do if the database size of the import program is different from that of the original database?

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.