Use the existing SQLite database and androidsqlite In the Android Program

Source: Internet
Author: User

Use the existing SQLite database and androidsqlite In the Android Program

In the Chinese search, I did not find a good article about how to use the database I created in advance in the Android Application. So I found this English article on Google and followed its steps, test successful, decided to give this article a rough translation, 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 we should have gone through a lot of discussions. This article is also directly referenced in some overstack answers. Share it with students in need.


Translation:

In most Android examples or tutorials, it is assumed that you need to create a database and insert new data while running the program, rather than using an independent database to be read in advance.

Here we will talk about how to use your own SQLite database stored in the "assets" folder, 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 normally.

1. Prepare the SQLite database file

Suppose you have created an sqlite database, and we need to modify it.

(Translator's note: The original Article here recommends an SQLite database management software, which I think can be followed by my preferences. in Windows, there are multiple visual SQlite database management software, you can easily read and edit databases. For example, I use sqlitestudio.

Open the database, add a new table "android_metadata", and insert a row of data. The specific SQL statement is as follows:

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')INSERT INTO "android_metadata" VALUES ('en_US')
(Note: The above two rows indicate the operations to be performed, which can be completed directly in sqlitesstudio)

Then you need to rename the primary id column of your data table to "_ id", so that Adroid will know how to bind the id column, you can easily edit data in the SQlite database management software.

After these two steps, your sqlite database file will be ready.

(Note: Here I keep the id column, that is, it is not renamed, and the test proves there is 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 under the "assets" folder and 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 will be created into the default system path               //of your application so we are gonna be able to overwrite that 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 application.     * @return true if it exists, false if it doesn't     */    private boolean checkDataBase(){     SQLiteDatabase checkDB = null;     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 done by transfering bytestream.     * */    private void copyDataBase() throws IOException{     //Open your local db as the input stream    InputStream myInput = 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, int 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 be easy       // to you to create adapters for your views. }

That's it.

Now you can create a new DataBaseHelper instance, call createDataBase (), and then call the openDataBase () method, remember to modify "YOUR_PACKAGE" in the DB_PATH string to your real package name (that is, 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;  }         ...




How to access the external SQLite database in android development is the best database for other applications with detailed instructions and code

This is all explained in this article. Please take a look at it and hope it can help developers.

Www.ibm.com/...qlite/

When using SQLite in android development, how can I use the first created

OpenOrCreateDatabase is used to open or create a database. If the database already exists, the existing

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.