SoFunction
Updated on 2025-03-08

Android database packaging instance code released with APK


import ;
import ;
import ;
import ;

import ;
import ;
import ;

import ;

/**
* copy database to apk package
 *
 * @author NGJ
 *
 */
public class DataBaseUtil {

 private Context context;
public static String dbName = "";// The name of the database
private static String DATABASE_PATH;// The path of the database in the mobile phone

 public DataBaseUtil(Context context) {
   = context;
  String packageName = ();
  DATABASE_PATH="/data/data/"+packageName+"/databases/";
 }

 /**
* Determine whether the database exists
  *
  * @return false or true
  */
 public boolean checkDataBase() {
  SQLiteDatabase db = null;
  try {
   String databaseFilename = DATABASE_PATH + dbName;
   db = (databaseFilename, null,SQLiteDatabase.OPEN_READONLY);
  } catch (SQLiteException e) {

  }
  if (db != null) {
   ();
  }
  return db != null ? true : false;
 }

 /**
* Copy the database to the specified folder of your phone
  *
  * @throws IOException
  */
 public void copyDataBase() throws IOException {
  String databaseFilenames = DATABASE_PATH + dbName;
  File dir = new File(DATABASE_PATH);
if (!())// To determine whether the folder exists, create a new one if it does not exist.
   ();
FileOutputStream os = new FileOutputStream(databaseFilenames);// Get the write stream of the database file
InputStream is = ().openRawResource();// Get the data stream of the database file
  byte[] buffer = new byte[8192];
  int count = 0;
  while ((count = (buffer)) > 0) {
   (buffer, 0, count);
   ();
  }
  ();
  ();
 }
}