How to access an existing sqlite database in Android?

試著忘記壹切 提交于 2019-12-17 08:23:23

问题


So far we have developed apps in android that create database on runtime. We like to know how can we access a pre-built or existing database/sqlite file in our android app? Please provide detail


回答1:


Take a look at the documentation for android.database.sqlite.SQLiteDatabase.

In particular, there's an openDatabase() command that will access a database given a file path.

SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, 0);

Just specify the path to your database as the path variable, and it should work.




回答2:


I have followed the same road and found two issues:

  1. Include the _id field on any table you create and make sure it is part of the columns to return when you query any table.
  2. You may run into an error like Failed to open the database. closing it.. This is because we are copying the database from an existing file instead of creating tables on top of a db created by the sqlite android API and the table android_metadata may not exist. For creating it just run the following query on your db:

    CREATE TABLE android_metadata (locale TEXT);

    And add the corresponding locale, for example en_US




回答3:


First copy your SDCARD and give it's path in the variable "DBNAME" in the following example. it will be something like "/sdcard/persons.db" if you are directly pulling it to sdcard.




回答4:


Use this for accessing database in application :

Context context = getApplicationContext();
context.getDatabasePath(DataBaseHelper.database_Name);


来源:https://stackoverflow.com/questions/1951805/how-to-access-an-existing-sqlite-database-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!