Android application development will SQLite and APK together to package the method _java

Source: Internet
Author: User
Tags flush int size mkdir sqlite sqlite database


After you create a new project in Eclipse, you will default to a assets directory, copy the prepared SQLite database directly to the directory in Eclipse, and then encode it in the main activity:


package com.test.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class DbtestActivity extends Activity {
 / ** Called when the activity is first created. * /
 @Override
 public void onCreate (Bundle savedInstanceState) {
 super.onCreate (savedInstanceState);
 setContentView (R.layout.main);

 // com.test.db is the package name of the program, please adjust it according to your own program
 // /data/data/com.test.db/
 // The databases directory is where the SQLite database is prepared and the default database storage directory for Android programs
 // The database name is test.db
 String DB_PATH = "/data/data/com.test.db/databases/";
 String DB_NAME = "test.db";

 // Check if the SQLite database file exists
 if ((new File (DB_PATH + DB_NAME)). exists () == false) {
  // If the SQLite database file does not exist, then check if the database directory exists
  File f = new File (DB_PATH);
  // If the database directory does not exist, create the directory
  if (! f.exists ()) {
  f.mkdir ();
  }

  try {
  // Get the prepared SQLite database under the assets directory as the input stream
  InputStream is = getBaseContext (). GetAssets (). Open (DB_NAME);
  // output stream
  OutputStream os = new FileOutputStream (DB_PATH + DB_NAME);

  // File writing
  byte [] buffer = new byte [1024];
  int length;
  while ((length = is.read (buffer))> 0) {
   os.write (buffer, 0, length);
  }

  // Close the file stream
  os.flush ();
  os.close ();
  is.close ();
  } catch (Exception e) {
  e.printStackTrace ();
  }
 }

 // Let's test if the database under /data/data/com.test.db/databases/ can work normally
 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase (DB_PATH + DB_NAME, null);
 Cursor cursor = database.rawQuery ("select * from test", null);

 if (cursor.getCount ()> 0) {
  cursor.moveToFirst ();
  try {
  // Solve Chinese garbled problem
  byte test [] = cursor.getBlob (0);
  String strtest = new String (test, "utf-8"). Trim ();

  // See if the output information is correct
  System.out.println (strtest);
  } catch (UnsupportedEncodingException e) {
  // TODO Auto-generated catch block
  e.printStackTrace ();
  }
 }
 cursor.close ();
 }
}


When the program starts, check that the database files are not there, and if they do not, they will copy our prepared database to which databases directory, and if the user uninstalls the program, the directory and the database will be uninstalled as well.



One more example.
The normal application database is placed in the/data/data/package name/database/test.db, when the application is published, the database is not released with the application.



So in order for our prepared data to work properly, we must be able to replicate the database itself to the SD card,



Implementation of copy RES/RAW/TEST.DB resources under the SD card/mnt/sdcard/test/test.db



The code is as follows:


Package zcping.syan.DBDefinition;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Java.io.InputStream;

Import ZCPING.SYAN.DRAGONBABY.R;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;

Import Android.util.Log; The public class releasedatabaseactivity{/** called the "the", "the" directory under the ". * * * *//SD card is private final String
 Database_path = android.os.Environment. getExternalStorageDirectory (). GetAbsolutePath () + "/db_exam";
 Database name Private final String database_filename = "db_exam.db";
 This context is required, no context, how can not achieve the copy operation of the database;
 Constructors must be passed in to the context, and the operation of the database takes the incoming public releasedatabaseactivity of this parameter (context ctx) {this.context = CTX;
  Public Sqlitedatabase OpenDatabase () {try {String databasefilename = Database_path + '/' + database_filename;
  File dir = new file (Database_path); Determine if there is a directory under the SD card that holds the database, or if it does not, create a new directory if (!dir.exists ()) {Dir.mkdir ();
  LOG.I ("Releasedatabaseactivity", "Dir made:" + Database_path);
  else {log.i ("releasedatabaseactivity", "dir exist:" + Database_path); try {//If the database already exists in the SD card directory, you do not need to re-create it, otherwise create the file and copy the/res/raw database file below if (!
   New file (DatabaseFileName)). Exists ()) {log.i ("releasedatabaseactivity", "File not exist:" + databasefilename);
   Res/raw database as output stream InputStream is = This.context.getResources (). Openrawresource (R.raw.db_exam);
   Test with int size = Is.available ();
   LOG.I ("Releasedatabaseactivity", "database_size:" + 1);
   LOG.I ("Releasedatabaseactivity", "Count:" + 0);
    Data stream for storing database information fileoutputstream fos = new FileOutputStream (databasefilename);
   byte[] buffer = new byte[8192];
   int count = 0;
   LOG.I ("Releasedatabaseactivity", "Count:" + count);
   Writes the data to the SD card directory while (count = is.read (buffer) > 0) {fos.write (buffer, 0, count);
   } fos.flush ();
   Fos.close ();
  Is.close (); \ catch (FileNotFoundException E{LOG.E ("Database", "File not Found");
  E.printstacktrace ();
  catch (IOException e) {log.e ("Database", "IO exception");
  E.printstacktrace ();
  //instantiated SD card on the database, DB as the return value, is behind all insert, delete, query operation excuses.
  Sqlitedatabase database = sqlitedatabase.openorcreatedatabase (databasefilename, NULL);

 return database;
 catch (Exception e) {} return null;

 }
}

The

has been tested, absolutely, and hopefully it will help.


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.