Using an existing SQLite database in an Android program

Source: Internet
Author: User
Tags sqlite database

This article has been migrated to code quiz , you can also check this article here , please pay more attention to my new technology blog codewenda.com




In the Chinese search, did not find a better about how to use their own pre-created database in the Android application of the article, so on Google to find this article in English, according to its steps, test success. decided to translate this article roughly, want to see the original can click here: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/. This article has more than 700 comments, so it should have been a lot of discussion. In some of Overstackflow's answers, this article was also quoted directly. Share to the students who need it.


President

In most examples of Android demos or tutorials, if you need to create a database and insert new data when the program executes, instead of using a separate, read-ahead database.

Here's how to use your own SQLite database stored in the "assets" directory, that is, how to copy your prepared database to the system database path of your Android program, so that the Sqlitedatabase API can read it properly.

1. Prepare the SQLite database file

If you have already created a SQLite database, we need to make some changes to it.

(Translator Note: Here is the original recommended a SQLite database management software.) This I think can follow their own preferences, the most windows below have a variety of visual SQLite database management software, can be easily read. Edit the database, for example, I'm using Sqlitestudio.

Open the database. Add a new table "Android_metadata", insert a row of data, detailed SQL such as the following:

CREATE TABLE "Android_metadata" ("locale" TEXT DEFAULT ' en_US ') INSERT into "Android_metadata" VALUES (' en_US ')
(Translator Note: The above two lines indicate the required operation, detailed can be completed directly in the Sqlitesstudio)

Then you need to name the primary ID rename of your data table "_id". So adroid will know how to bind the ID column, you can very easy in the SQLite database management software for column editing.

After these two steps, your SQLite database file is ready.

(Translator Note: I have reserved the ID column here, that is not renamed it, Test proved to be no problem)


2. Copy, open and access the database in your Android program

Now put the database files you have prepared in the previous step below the "assets" directory. Then create a database helper class by inheriting the Sqliteopenhelper class.

Your Databasehelper class can be roughly as follows:

public class Databasehelper extends sqliteopenhelper{//the Android ' s default system path of your application database    .     private static String Db_path = "/data/data/your_package/databases/";     private static String db_name = "Mydbname";      Private Sqlitedatabase myDataBase;     Private final Context Mycontext;  /** * Constructor * Takes and keeps a reference of the passed context in order to access to the application assets     and resources.        * @param context */public databasehelper (context context) {Super (context, db_name, NULL, 1);    This.mycontext = context;     }/** * Creates a empty database on the system and rewrites it with your own database.     * */public void CreateDatabase () throws ioexception{Boolean dbexist = Checkdatabase (); if (dbexist) {//do nothing-database already exist}else{//by calling this method and empty database would be CR Eated into the default system path//of your applicationSo we is gonna is able to overwrite the database with our database.         This.getreadabledatabase ();     try {copydatabase ();         } catch (IOException e) {throw new error ("Error copying database"); }}}/** * Check If the database already exist to avoid re-copying the file each time you open the Applica     tion. * @return True if it exists, false if it doesn ' t */private Boolean checkdatabase () {Sqlitedatabase CheckDB = n     Ull    try{String MyPath = Db_path + db_name;     CheckDB = sqlitedatabase.opendatabase (MyPath, NULL, sqlitedatabase.open_readonly);     }catch (sqliteexception e) {//database does ' t exist yet.     } if (CheckDB! = null) {checkdb.close (); } return CheckDB! = null?    True:false; }/** * Copies your database from your local assets-folder to the just created empty database in the * system     folder, from where it can be accessed and handled. * This is do by transfering bytesTream. * */private void Copydatabase () throws ioexception{//open your local db as the input stream InputStream Myinpu     t = mycontext.getassets (). open (db_name);     Path to the just created empty db String outfilename = Db_path + db_name;     Open the empty DB as the output stream outputstream myoutput = new FileOutputStream (outfilename);    Transfer bytes from the Inputfile to the outputfile byte[] buffer = new byte[1024];    int length;    while (length = myinput.read (buffer)) >0) {myoutput.write (buffer, 0, length);    }//close the Streams Myoutput.flush ();    Myoutput.close ();     Myinput.close ();    } public void OpenDatabase () throws sqlexception{//open the database String MyPath = Db_path + db_name;     MyDataBase = sqlitedatabase.opendatabase (MyPath, NULL, sqlitedatabase.open_readonly);         } @Overridepublic synchronized void Close () {if (myDataBase! = null) mydatabase.close (); Super.close (); } @Overridepublic void OnCreate (Sqlitedatabase db) {} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, in       T newversion) {}//Add Your public helper methods to access and get content from the database. You could return cursors by doing "return Mydatabase.query (...)" So it ' d is easy//to ' Create adapters fo R your views. }

that's it.

Now you are able to create a new Databasehelper instance and then call CreateDatabase (). Then call the OpenDatabase () method and remember to change the Db_path string "Your_package" to your real package name (i.e. Com.examplename.myapp)

Here is the sample code:

...         Databasehelper mydbhelper = new Databasehelper ();        Mydbhelper = new Databasehelper (this);         try {         mydbhelper.createdatabase ();  } catch (IOException IoE) {  throw new Error ("Unable to create database");  }  try {  mydbhelper.opendatabase ();  } catch (SQLException Sqle) {  throw sqle;  }         ...



Using an existing SQLite database in an Android program

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.