Use pre created SQLite database for Android project in kotlin










0















I am trying to use an already existing sqLite database in my android app. I have verified that it is loaded into the project in the assets folder and I can browse it in DB browser when I open it directly from the project.



This is the schema for the table I am trying to query



CREATE TABLE "ACTIVITY_LIST_TBL" ( 
`_ID` INTEGER NOT NULL,
`ACT_NAME` VARCHAR NOT NULL,
`ACT_CODE` VARCHAR,
`IS_ACTIVE` INTEGER DEFAULT -1,
PRIMARY KEY(`_ID`) )


Below is the activity that creates the sqlite helper and then on a button click I execute a query on the ACTIVITY_LIST_TBL. When the query is executed this exception is thrown:




android.database.sqlite.SQLiteException: no such table: ACTIVITY_LIST_TBL (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM ACTIVITY_LIST_TBL




class CalendarActivity : AppCompatActivity() {

private var cursor:Cursor? = null

override fun onCreate(savedInstanceState:Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.calendar_activity)

findViewById<Button>(R.id.CalTestButton).setOnClickListener

val myDbHelper = DatabaseHelper(this)

try myDbHelper.createDataBase()
catch (ioE: IOException) throw Error("Unable to create database")

try myDbHelper.openDataBase()
catch (sqlE: SQLException) throw sqlE

Toast.makeText(this, "Successfully Imported", Toast.LENGTH_SHORT).show()

cursor = myDbHelper.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)

cursor?.let
if (cursor!!.moveToFirst())
do
Toast.makeText(this,
"ACTIVITY_ID: " + cursor!!.getString(0) + "n" +
"ACTIVITY_NAME: " + cursor!!.getString(1) + "n" +
"ACTIVITY_CODE: " + cursor!!.getString(2) + "n" +
"IS_ACTIVE: " + cursor!!.getString(3),
Toast.LENGTH_LONG).show()
while (cursor!!.moveToNext())





This is my db helper (the actual query I am running can be found at the bottom of this file - I purposely hardcoded the table name for debugging):



class DatabaseHelper(private val myContext: Context) : SQLiteOpenHelper(myContext, DB_NAME, null, DB_VERSION) 

private var DB_PATH: String? = null
private var calendarDatabase: SQLiteDatabase? = null


companion object
private val DB_NAME = "calendarDb"
private val DB_VERSION = 1




init
this.DB_PATH = "/data/data/" + myContext.packageName + "/" + "databases/"
Timber.e("Path 1: $DB_PATH")



@Throws(IOException::class)
fun createDataBase()
val dbExist = checkDataBase()
if (dbExist)
else
this.readableDatabase
try
copyDataBase()
catch (e: IOException)
throw Error("Error copying database")





private fun checkDataBase(): Boolean
var checkDB: SQLiteDatabase? = null
try
val myPath = DB_PATH!! + DB_NAME
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)
catch (e: SQLiteException)


checkDB?.close()
return if (checkDB != null) true else false


@Throws(IOException::class)
private fun copyDataBase()
val myInput = myContext.assets.open(DB_NAME)
val outFileName = DB_PATH!! + DB_NAME
val myOutput = FileOutputStream(outFileName)
val buffer = ByteArray(10)

var length: Int = myInput.read(buffer)

while (length > 0)
myOutput.write(buffer, 0, length)
length = myInput.read(buffer)

myOutput.flush()
myOutput.close()
myInput.close()



@Throws(SQLException::class)
fun openDataBase()
val myPath = DB_PATH!! + DB_NAME
calendarDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)



@Synchronized
override fun close()
if (calendarDatabase != null)
calendarDatabase!!.close()
super.close()



override fun onCreate(db: SQLiteDatabase)

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
if (newVersion > oldVersion)
try
copyDataBase()
catch (e: IOException)
e.printStackTrace()





fun query(table: String, columns: Array<String>?, selection: String?, selectionArgs: Array<String>?, groupBy: String?, having: String?, orderBy: String?): Cursor

return calendarDatabase!!.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)





It seems like I must be loading in the database in the wrong way somehow, any help is greatly appreciated.



Please note I have already set up the database to be compatible with Android by executing these lines in the db browser:




CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')



INSERT INTO "android_metadata" VALUES ('en_US')




I do not think this matters (I have already tested this), but I decided not to make every table's primary key '_id'










share|improve this question




























    0















    I am trying to use an already existing sqLite database in my android app. I have verified that it is loaded into the project in the assets folder and I can browse it in DB browser when I open it directly from the project.



    This is the schema for the table I am trying to query



    CREATE TABLE "ACTIVITY_LIST_TBL" ( 
    `_ID` INTEGER NOT NULL,
    `ACT_NAME` VARCHAR NOT NULL,
    `ACT_CODE` VARCHAR,
    `IS_ACTIVE` INTEGER DEFAULT -1,
    PRIMARY KEY(`_ID`) )


    Below is the activity that creates the sqlite helper and then on a button click I execute a query on the ACTIVITY_LIST_TBL. When the query is executed this exception is thrown:




    android.database.sqlite.SQLiteException: no such table: ACTIVITY_LIST_TBL (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM ACTIVITY_LIST_TBL




    class CalendarActivity : AppCompatActivity() {

    private var cursor:Cursor? = null

    override fun onCreate(savedInstanceState:Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.calendar_activity)

    findViewById<Button>(R.id.CalTestButton).setOnClickListener

    val myDbHelper = DatabaseHelper(this)

    try myDbHelper.createDataBase()
    catch (ioE: IOException) throw Error("Unable to create database")

    try myDbHelper.openDataBase()
    catch (sqlE: SQLException) throw sqlE

    Toast.makeText(this, "Successfully Imported", Toast.LENGTH_SHORT).show()

    cursor = myDbHelper.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)

    cursor?.let
    if (cursor!!.moveToFirst())
    do
    Toast.makeText(this,
    "ACTIVITY_ID: " + cursor!!.getString(0) + "n" +
    "ACTIVITY_NAME: " + cursor!!.getString(1) + "n" +
    "ACTIVITY_CODE: " + cursor!!.getString(2) + "n" +
    "IS_ACTIVE: " + cursor!!.getString(3),
    Toast.LENGTH_LONG).show()
    while (cursor!!.moveToNext())





    This is my db helper (the actual query I am running can be found at the bottom of this file - I purposely hardcoded the table name for debugging):



    class DatabaseHelper(private val myContext: Context) : SQLiteOpenHelper(myContext, DB_NAME, null, DB_VERSION) 

    private var DB_PATH: String? = null
    private var calendarDatabase: SQLiteDatabase? = null


    companion object
    private val DB_NAME = "calendarDb"
    private val DB_VERSION = 1




    init
    this.DB_PATH = "/data/data/" + myContext.packageName + "/" + "databases/"
    Timber.e("Path 1: $DB_PATH")



    @Throws(IOException::class)
    fun createDataBase()
    val dbExist = checkDataBase()
    if (dbExist)
    else
    this.readableDatabase
    try
    copyDataBase()
    catch (e: IOException)
    throw Error("Error copying database")





    private fun checkDataBase(): Boolean
    var checkDB: SQLiteDatabase? = null
    try
    val myPath = DB_PATH!! + DB_NAME
    checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)
    catch (e: SQLiteException)


    checkDB?.close()
    return if (checkDB != null) true else false


    @Throws(IOException::class)
    private fun copyDataBase()
    val myInput = myContext.assets.open(DB_NAME)
    val outFileName = DB_PATH!! + DB_NAME
    val myOutput = FileOutputStream(outFileName)
    val buffer = ByteArray(10)

    var length: Int = myInput.read(buffer)

    while (length > 0)
    myOutput.write(buffer, 0, length)
    length = myInput.read(buffer)

    myOutput.flush()
    myOutput.close()
    myInput.close()



    @Throws(SQLException::class)
    fun openDataBase()
    val myPath = DB_PATH!! + DB_NAME
    calendarDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)



    @Synchronized
    override fun close()
    if (calendarDatabase != null)
    calendarDatabase!!.close()
    super.close()



    override fun onCreate(db: SQLiteDatabase)

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
    if (newVersion > oldVersion)
    try
    copyDataBase()
    catch (e: IOException)
    e.printStackTrace()





    fun query(table: String, columns: Array<String>?, selection: String?, selectionArgs: Array<String>?, groupBy: String?, having: String?, orderBy: String?): Cursor

    return calendarDatabase!!.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)





    It seems like I must be loading in the database in the wrong way somehow, any help is greatly appreciated.



    Please note I have already set up the database to be compatible with Android by executing these lines in the db browser:




    CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')



    INSERT INTO "android_metadata" VALUES ('en_US')




    I do not think this matters (I have already tested this), but I decided not to make every table's primary key '_id'










    share|improve this question


























      0












      0








      0








      I am trying to use an already existing sqLite database in my android app. I have verified that it is loaded into the project in the assets folder and I can browse it in DB browser when I open it directly from the project.



      This is the schema for the table I am trying to query



      CREATE TABLE "ACTIVITY_LIST_TBL" ( 
      `_ID` INTEGER NOT NULL,
      `ACT_NAME` VARCHAR NOT NULL,
      `ACT_CODE` VARCHAR,
      `IS_ACTIVE` INTEGER DEFAULT -1,
      PRIMARY KEY(`_ID`) )


      Below is the activity that creates the sqlite helper and then on a button click I execute a query on the ACTIVITY_LIST_TBL. When the query is executed this exception is thrown:




      android.database.sqlite.SQLiteException: no such table: ACTIVITY_LIST_TBL (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM ACTIVITY_LIST_TBL




      class CalendarActivity : AppCompatActivity() {

      private var cursor:Cursor? = null

      override fun onCreate(savedInstanceState:Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.calendar_activity)

      findViewById<Button>(R.id.CalTestButton).setOnClickListener

      val myDbHelper = DatabaseHelper(this)

      try myDbHelper.createDataBase()
      catch (ioE: IOException) throw Error("Unable to create database")

      try myDbHelper.openDataBase()
      catch (sqlE: SQLException) throw sqlE

      Toast.makeText(this, "Successfully Imported", Toast.LENGTH_SHORT).show()

      cursor = myDbHelper.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)

      cursor?.let
      if (cursor!!.moveToFirst())
      do
      Toast.makeText(this,
      "ACTIVITY_ID: " + cursor!!.getString(0) + "n" +
      "ACTIVITY_NAME: " + cursor!!.getString(1) + "n" +
      "ACTIVITY_CODE: " + cursor!!.getString(2) + "n" +
      "IS_ACTIVE: " + cursor!!.getString(3),
      Toast.LENGTH_LONG).show()
      while (cursor!!.moveToNext())





      This is my db helper (the actual query I am running can be found at the bottom of this file - I purposely hardcoded the table name for debugging):



      class DatabaseHelper(private val myContext: Context) : SQLiteOpenHelper(myContext, DB_NAME, null, DB_VERSION) 

      private var DB_PATH: String? = null
      private var calendarDatabase: SQLiteDatabase? = null


      companion object
      private val DB_NAME = "calendarDb"
      private val DB_VERSION = 1




      init
      this.DB_PATH = "/data/data/" + myContext.packageName + "/" + "databases/"
      Timber.e("Path 1: $DB_PATH")



      @Throws(IOException::class)
      fun createDataBase()
      val dbExist = checkDataBase()
      if (dbExist)
      else
      this.readableDatabase
      try
      copyDataBase()
      catch (e: IOException)
      throw Error("Error copying database")





      private fun checkDataBase(): Boolean
      var checkDB: SQLiteDatabase? = null
      try
      val myPath = DB_PATH!! + DB_NAME
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)
      catch (e: SQLiteException)


      checkDB?.close()
      return if (checkDB != null) true else false


      @Throws(IOException::class)
      private fun copyDataBase()
      val myInput = myContext.assets.open(DB_NAME)
      val outFileName = DB_PATH!! + DB_NAME
      val myOutput = FileOutputStream(outFileName)
      val buffer = ByteArray(10)

      var length: Int = myInput.read(buffer)

      while (length > 0)
      myOutput.write(buffer, 0, length)
      length = myInput.read(buffer)

      myOutput.flush()
      myOutput.close()
      myInput.close()



      @Throws(SQLException::class)
      fun openDataBase()
      val myPath = DB_PATH!! + DB_NAME
      calendarDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)



      @Synchronized
      override fun close()
      if (calendarDatabase != null)
      calendarDatabase!!.close()
      super.close()



      override fun onCreate(db: SQLiteDatabase)

      override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
      if (newVersion > oldVersion)
      try
      copyDataBase()
      catch (e: IOException)
      e.printStackTrace()





      fun query(table: String, columns: Array<String>?, selection: String?, selectionArgs: Array<String>?, groupBy: String?, having: String?, orderBy: String?): Cursor

      return calendarDatabase!!.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)





      It seems like I must be loading in the database in the wrong way somehow, any help is greatly appreciated.



      Please note I have already set up the database to be compatible with Android by executing these lines in the db browser:




      CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')



      INSERT INTO "android_metadata" VALUES ('en_US')




      I do not think this matters (I have already tested this), but I decided not to make every table's primary key '_id'










      share|improve this question
















      I am trying to use an already existing sqLite database in my android app. I have verified that it is loaded into the project in the assets folder and I can browse it in DB browser when I open it directly from the project.



      This is the schema for the table I am trying to query



      CREATE TABLE "ACTIVITY_LIST_TBL" ( 
      `_ID` INTEGER NOT NULL,
      `ACT_NAME` VARCHAR NOT NULL,
      `ACT_CODE` VARCHAR,
      `IS_ACTIVE` INTEGER DEFAULT -1,
      PRIMARY KEY(`_ID`) )


      Below is the activity that creates the sqlite helper and then on a button click I execute a query on the ACTIVITY_LIST_TBL. When the query is executed this exception is thrown:




      android.database.sqlite.SQLiteException: no such table: ACTIVITY_LIST_TBL (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM ACTIVITY_LIST_TBL




      class CalendarActivity : AppCompatActivity() {

      private var cursor:Cursor? = null

      override fun onCreate(savedInstanceState:Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.calendar_activity)

      findViewById<Button>(R.id.CalTestButton).setOnClickListener

      val myDbHelper = DatabaseHelper(this)

      try myDbHelper.createDataBase()
      catch (ioE: IOException) throw Error("Unable to create database")

      try myDbHelper.openDataBase()
      catch (sqlE: SQLException) throw sqlE

      Toast.makeText(this, "Successfully Imported", Toast.LENGTH_SHORT).show()

      cursor = myDbHelper.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)

      cursor?.let
      if (cursor!!.moveToFirst())
      do
      Toast.makeText(this,
      "ACTIVITY_ID: " + cursor!!.getString(0) + "n" +
      "ACTIVITY_NAME: " + cursor!!.getString(1) + "n" +
      "ACTIVITY_CODE: " + cursor!!.getString(2) + "n" +
      "IS_ACTIVE: " + cursor!!.getString(3),
      Toast.LENGTH_LONG).show()
      while (cursor!!.moveToNext())





      This is my db helper (the actual query I am running can be found at the bottom of this file - I purposely hardcoded the table name for debugging):



      class DatabaseHelper(private val myContext: Context) : SQLiteOpenHelper(myContext, DB_NAME, null, DB_VERSION) 

      private var DB_PATH: String? = null
      private var calendarDatabase: SQLiteDatabase? = null


      companion object
      private val DB_NAME = "calendarDb"
      private val DB_VERSION = 1




      init
      this.DB_PATH = "/data/data/" + myContext.packageName + "/" + "databases/"
      Timber.e("Path 1: $DB_PATH")



      @Throws(IOException::class)
      fun createDataBase()
      val dbExist = checkDataBase()
      if (dbExist)
      else
      this.readableDatabase
      try
      copyDataBase()
      catch (e: IOException)
      throw Error("Error copying database")





      private fun checkDataBase(): Boolean
      var checkDB: SQLiteDatabase? = null
      try
      val myPath = DB_PATH!! + DB_NAME
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)
      catch (e: SQLiteException)


      checkDB?.close()
      return if (checkDB != null) true else false


      @Throws(IOException::class)
      private fun copyDataBase()
      val myInput = myContext.assets.open(DB_NAME)
      val outFileName = DB_PATH!! + DB_NAME
      val myOutput = FileOutputStream(outFileName)
      val buffer = ByteArray(10)

      var length: Int = myInput.read(buffer)

      while (length > 0)
      myOutput.write(buffer, 0, length)
      length = myInput.read(buffer)

      myOutput.flush()
      myOutput.close()
      myInput.close()



      @Throws(SQLException::class)
      fun openDataBase()
      val myPath = DB_PATH!! + DB_NAME
      calendarDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY)



      @Synchronized
      override fun close()
      if (calendarDatabase != null)
      calendarDatabase!!.close()
      super.close()



      override fun onCreate(db: SQLiteDatabase)

      override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int)
      if (newVersion > oldVersion)
      try
      copyDataBase()
      catch (e: IOException)
      e.printStackTrace()





      fun query(table: String, columns: Array<String>?, selection: String?, selectionArgs: Array<String>?, groupBy: String?, having: String?, orderBy: String?): Cursor

      return calendarDatabase!!.query("ACTIVITY_LIST_TBL", null, null, null, null, null, null)





      It seems like I must be loading in the database in the wrong way somehow, any help is greatly appreciated.



      Please note I have already set up the database to be compatible with Android by executing these lines in the db browser:




      CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')



      INSERT INTO "android_metadata" VALUES ('en_US')




      I do not think this matters (I have already tested this), but I decided not to make every table's primary key '_id'







      android database sqlite






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 20:47







      D. Maul

















      asked Nov 12 '18 at 21:18









      D. MaulD. Maul

      348




      348






















          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270269%2fuse-pre-created-sqlite-database-for-android-project-in-kotlin%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270269%2fuse-pre-created-sqlite-database-for-android-project-in-kotlin%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Darth Vader #20

          Ondo