Android application development method to package SQLite and APK together

  • 2020-04-01 04:09:38
  • OfStack

After creating a new project in Eclipse, there will be an assets directory by default. Directly copy the prepared SQLite database into this directory in Eclipse, and then code 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 {
 
 @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 the place to put the SQLite database and the default database storage directory for the Android program
 //The database is called test.db
 String DB_PATH = "/data/data/com.test.db/databases/";
 String DB_NAME = "test.db";

 //Check for the existence of SQLite database files
 if ((new File(DB_PATH + DB_NAME)).exists() == false) {
  //If the SQLite database file does not exist, check again to see if the database directory exists
  File f = new File(DB_PATH);
  //If the database directory does not exist, create a new one
  if (!f.exists()) {
  f.mkdir();
  }

  try {
  //We get the assets directory and we implement the prepared SQLite database as the input stream
  InputStream is = getBaseContext().getAssets().open(DB_NAME);
  //The output stream
  OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);

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

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

 //The following tests/data/data/com. Test. The db/databases/database 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 the problem of Chinese garbled code
  byte test[] = cursor.getBlob(0);
  String strtest = new String(test, "utf-8").trim();

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

When the program starts, we go back and check whether the database file is there. If it is not, we will copy the database we prepared to the database directory, and if the user uninstalls the program, the directory and database will be uninstalled.

Let's do another example.
The normal application database is put in /data/data/ package name /database/test.db. When the application is published, the database will not be published with the application.

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

Implement copy res/raw/test.db under the resource copy to SD card under/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;

public class ReleaseDataBaseActivity{
 
 //SD card under the directory
 private final String DATABASE_PATH = android.os.Environment
  .getExternalStorageDirectory().getAbsolutePath() + "/db_exam";
 //The database name
 private final String DATABASE_FILENAME = "db_exam.db";
 //This context is required, and without a context, you can't copy the database;
 private Context context;
 //The constructor must pass in the Context, and the database operations are passed in with this parameter
 public ReleaseDataBaseActivity(Context ctx) {
 this.context = ctx;
 }

 public SQLiteDatabase OpenDataBase() {
 try {
  String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
  File dir = new File(DATABASE_PATH);
  //Determine whether there is a directory to store the database under the SD card, if 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, there is no need to recreate it, otherwise create the file and copy the database file under /res/raw
  if (!(new File(databaseFilename)).exists()) {
   Log.i("ReleaseDataBaseActivity", "file not exist:"
    + databaseFilename);
   //The /res/raw database as the output stream
   InputStream is = this.context.getResources().openRawResource(
    R.raw.db_exam);
   //The test
   int size = is.available();
   Log.i( "ReleaseDataBaseActivity", "DATABASE_SIZE:" + 1 );
   Log.i("ReleaseDataBaseActivity", "count:" + 0);
   //A data stream used to hold database information
   FileOutputStream fos = new FileOutputStream(
    databaseFilename);
    byte[] buffer = new byte[8192];
   int count = 0;
   Log.i("ReleaseDataBaseActivity", "count:" + count);
   //Write 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();
  }
  //Instantiate the database on the sd card, and the database as the return value is the excuse for all insert, delete and query operations.
  SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
   databaseFilename, null);
  return database;

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

After testing, absolutely good, hope to help you.


Related articles: