N
N
newdancer2016-07-03 17:45:29
Android
newdancer, 2016-07-03 17:45:29

How to add a prebuilt SQLite database to Android?

Tried like this, made a separate class:

public class DataBaseHelper extends SQLiteOpenHelper
{
  // путь к базе
  private static String DB_PATH = "/data/data/net.kinomovies.stv_base/databases/";
  private static String DB_NAME = "test";
  static final  String DB_TABLE = "test";
  private static final int SCHEMA = 1; // версия базы данных

  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_NAME = "itemname";
  public static final String COLUMN_PRICE = "price";
  public static final String COLUMN_COUNT = "itemcount";
  public SQLiteDatabase myDataBase;
  private final Context mContext;

  // конструктор
  public DataBaseHelper(Context context)
  {
    super(context, DB_NAME, null, SCHEMA);
    this.mContext = context;
  }

  // создаем пустую и перезаписываем нашей
  public void createDataBase() throws IOException
  {
    boolean dbExist = checkDataBase();

    if(dbExist){

    }else{

      this.getReadableDatabase();

      try {
        copyDataBase();
      } catch (IOException e) {
        throw new Error("Error copying database");
      }
    }
  }

  // провекра на существование базы
  private boolean checkDataBase()
  {
    SQLiteDatabase checkDB = null;

    try{
      String myPath = DB_PATH + DB_NAME;
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }catch(SQLiteException e){
      //база еще не существует
    }
    if(checkDB != null){
      checkDB.close();
    }
    return checkDB != null ? true : false;
  }

  // копируем базу вместо новой
  private void copyDataBase() throws IOException
  {
    //Открываем локальную БД как входящий поток
    InputStream myInput = mContext.getAssets().open(DB_NAME);

    //Путь ко вновь созданной БД
    String outFileName = DB_PATH + DB_NAME;

    //Открываем пустую базу данных как исходящий поток
    OutputStream myOutput = new FileOutputStream(outFileName);

    //перемещаем байты из входящего файла в исходящий
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0)
    {
      myOutput.write(buffer, 0, length);
    }

    //закрываем потоки
    myOutput.flush();
    myOutput.close();
    myInput.close();
  }

  public void openDataBase() throws SQLException
  {
    //открываем БД
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  }

  @Override
  public synchronized void close()
  {
    if(myDataBase != null)
      myDataBase.close();
    super.close();
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}

put the test database into the assets folder.
But the application crashes with errors:
07-03 17:33:27.584 23739-23739/net.kinomovies.stv_base E/SQLiteLog: (28) failed to open "/data/data/net.kinomovies.stv_base/databases/test" with flag (131072) and mode_t (0) due to error (2)
07-03 17:33:27.584 23739-23739/net.kinomovies.stv_base E/SQLiteLog: (14) cannot open file at line 32557 of [b3bb660af9]
07-03 17:33:27.584 23739-23739/net.kinomovies.stv_base E/SQLiteLog: (14) os_unix.c:32557: (2) open(/data/data/net.kinomovies.stv_base/databases/test) - 
07-03 17:33:27.594 23739-23739/net.kinomovies.stv_base E/SQLiteDatabase: Failed to open database '/data/data/net.kinomovies.stv_base/databases/test'.
                                                                         android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 1294): Could not open database
                                                                         #################################################################
                                                                         Error Code : 1294 (SQLITE_CANTOPEN_ENOENT)
                                                                         Caused By : Specified directory or database file does not exist.
                                                                         	(unknown error (code 1294): Could not open database)
                                                                         #################################################################

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Kubashevsky, 2016-07-07
@Dehax

There is a ready-made solution in the form of a library . An example of using the link, the repository also contains various example projects .
In Gradle it connects like this:

dependencies {
    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
}

You need to inherit the class SQLiteAssetHelper, specify the name of the file with the base in the constructor, and put the file with the base in the folderassets/databases/your_database_name.db

S
SofroN, 2016-07-04
@SofroN

private static String DB_PATH = "/data/data/net.kinomovies.stv_base/databases/";

storing the absolute path to the database is a bad idea, use special methods to get the path. something like getDataDir (see the documentation for the exact name)
is tantamount to
return checkDB != null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question