SQLite data application and initialization for Android phone development

Source: Internet
Author: User
Tags sqlite

Creating a Database

Android does not automatically provide a database. Using SQLite in an Android application, you must create your own database, and then create tables, indexes, and fill data. Android provides sqliteopenhelper to help you create a database, and you can easily create a database just by inheriting the Sqliteopenhelper class. The Sqliteopenhelper class encapsulates the logic used to create and update databases, depending on the needs of the development application. Sqliteopenhelper subclass, you need to implement at least three methods:

• Constructor, calling the constructor of the parent class Sqliteopenhelper. This method requires four parameters: a context environment (for example, an activity), a database name, an optional cursor factory (usually Null), and an integer representing the version of the database model you are using.
The OnCreate () method, which requires a Sqlitedatabase object as a parameter, to populate the table and initialize the data on demand.
Onupgrage () method, it requires three parameters, a Sqlitedatabase object, an old version number and a new version number, so you can see how to transfer a database from the old model to the new model.
The following sample code shows how to inherit Sqliteopenhelper to create a database:

The code is as follows Copy Code

public class Databasehelper extends Sqliteopenhelper {


Databasehelper (context context, String name, cursorfactory cursorfactory, int version)


{


Super (context, name, cursorfactory, version);


}





@Override


public void OnCreate (Sqlitedatabase db) {


TODO operations on a database after the database is created


}





@Override


public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {


TODO Change the operation of the database version


}





@Override


public void OnOpen (Sqlitedatabase db) {


Super.onopen (DB);


TODO first executes each time the database is successfully opened


}


}



Next, we'll discuss how to create a table, insert data, delete a table, and so on. Call the Getreadabledatabase () or Getwriteabledatabase () method, and you can get the Sqlitedatabase instance, which is specifically called, depending on whether you need to change the contents of the database:

The code is as follows Copy Code
db= (New Databasehelper (GetContext ())). Getwritabledatabase ();
return (db = = null)? False:true;


The above code returns an instance of the Sqlitedatabase class, and you can query or modify the database using this object.

When you have finished working on the database (for example, your activity has been turned off), you need to call the Sqlitedatabase close () method to release the database connection.

The data for each program in the Android system is stored under/data/data/(package name)/directory, and the database is in the/dababases/directory.
So, you just use FileInputStream to read the original database, and then use FileOutputStream to read the contents of the write to that directory can be.

Action method:
1. Include the original database in the Res/raw directory of the project source code.
2. Create a class to control the database. As follows:


Code

The code is as follows Copy Code

Public class databasemanager{
                 private final int buffer_size = 400000;
                public static Final String db_name = "mydatabase.db"; Saved database file name
                public static final String package_name = "com.android.ImportDBTest";//Package name
                 public static final String Db_path = "/data"
  & nbsp;                  + Environment.getdatadirectory (). GetAbsolutePath () + "/"
                      + package_name; The location of the database in the phone

Private Sqlitedatabase database;
private context;

Dbmanager (Context context) {
This.context = context;
}

public void OpenDatabase () {
This.database = this.opendatabase (Db_path + "/" + db_name);
}

Private Sqlitedatabase OpenDatabase (String dbfile) {


try {


if (!) ( New file (DBFile). Exists ())) {//To determine if the database file exists, if not, perform the import, or open the database directly


InputStream is = This.context.getResources (). Openrawresource (


R.raw.mydatabase); The database you want to import


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;


}

Then, when you need to use the database, instantiate a Databasemanager class and call its OpenDatabase method to return a
Sqlitedatabase the object ... As follows:
Code

The code is as follows Copy Code

Sqlitedatabase db = new Dbmanager (this). OpenDatabase ();


This is just one corner of Android phone development.

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.