Using an existing SQLite database in an Android program

Source: Internet
Author: User
Tags sqlite database

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 English article, 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 Overstack's answers, this article was also quoted directly. Share it with students in need.


President

In most Android samples or tutorials, it is assumed that you need to create a database and insert new data while the program is running, rather than using a separate, pre-read database.

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

1. Prepare the SQLite database file

Suppose you have created a SQLite database and we need to make some changes to it.

(Translator Note: Here the original is recommended a SQLite database management software, this I think can follow their own preferences, the most windows under a variety of visual SQLite database management software, you can easily read, edit the database, for example, I use the Sqlitestudio

Open the database, add a new table "Android_metadata", insert a row of data, the specific SQL is as follows:

CREATE TABLE "Android_metadata" ("locale" TEXT DEFAULT ' en_US ') INSERT into "Android_metadata" VALUES (' en_US ')
(Translator Note: The above two lines indicate what needs to be done, can be done directly in Sqlitesstudio)

Then you need to name the primary ID rename of your data table "_id" so that adroid will know how to bind the ID column, and you can easily edit the column in SQLite database management software.

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

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


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

Now put the database file you have prepared in the next step under the "Assets" folder, and then you can create a DB 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 can create a new Databasehelper instance, then call CreateDatabase (), and then call the OpenDatabase () method, remembering to modify the Db_path string in the "Your_package" For your real package name (i.e. Com.examplename.myapp)

The following 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

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.