Android:访问带有 .sqlite 扩展名的资产文件夹 sqlite 数据库文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2605555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: Accessing assets folder sqlite database file with .sqlite extension
提问by Ashish Mishra
How to read data from the assets folder sqlite database file with .sqlite extension in my Android application?
如何从我的 Android 应用程序中扩展名为 .sqlite 的资产文件夹 sqlite 数据库文件中读取数据?
回答by Jaydeep Khamar
Try this code:
试试这个代码:
public class DataBaseHelper extends SQLiteOpenHelper {
private Context mycontext;
//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
+ mycontext.getApplicationContext().getPackageName()
+ "/databases/";*/
public DataBaseHelper(Context context) throws IOException {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if (dbexist) {
//System.out.println("Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}
public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if(dbexist) {
//System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch(IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
//checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
checkdb = dbfile.exists();
} catch(SQLiteException e) {
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases /(datbasename).sqlite");
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0) {
myoutput.write(buffer,0,length);
}
//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
public void opendatabase() throws SQLException {
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close() {
if(myDataBase != null) {
myDataBase.close();
}
super.close();
}
}
回答by Nikhil Ranjan
Place old database (old.db) in your asset folder. Type this inside onCreate() of your activity:
将旧数据库 (old.db) 放在您的资产文件夹中。在您的活动的 onCreate() 中输入:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
//=======Code For copying Existing Database file to system folder for use====//
// Copying Existing Database into system folder
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/data.db";
File f = new File(destPath);
if(!f.exists()){
Log.v(TAG,"File Not Exist");
InputStream in = getAssets().open("old.db");
OutputStream out = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
Log.v("TAG","ioexeption");
e.printStackTrace();
}
DBManager dbManager = new DBManager(this);
Log.v(TAG,"Database is there with version: "+dbManager.getReadableDatabase().getVersion());
String sql = "select * from prizes";
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
Log.v(TAG,"Query Result:"+cursor);
cursor.close();
db.close();
dbManager.close();
....
}
Now you have to make a DBManager Class which subclasses SQLiteOpenHelper . Insert the abstract method and constructor. Don't forget to type correct database name inside super() of dbHelper.
现在您必须创建一个 DBManager 类,它是 SQLiteOpenHelper 的子类。插入抽象方法和构造函数。不要忘记在 dbHelper 的 super() 中输入正确的数据库名称。
public class DBManager extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DATABASES";
public DBManager(Context context) {
super(context, "data.db", null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.v(TAG,"On create Called:"+db.getPath());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Now you can access database by instantiating DBManager.
现在您可以通过实例化 DBManager 来访问数据库。
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
...
Don't forget to close database or u will get a SQLiteDatabaseNotClosed Exception.
不要忘记关闭数据库,否则你会得到一个 SQLiteDatabaseNotClosed 异常。
db.close();
dbManager.close();
回答by Jon
Its important that in the tutorial, when you call the file, make sure you pass the application context getApplicationContext()
such that you have access to the correct assets, otherwise you might get a FileNotFound Exception.
重要的是,在本教程中,当您调用文件时,请确保您传递了应用程序上下文getApplicationContext()
,以便您可以访问正确的资产,否则您可能会收到 FileNotFound 异常。
回答by Sangeeth Nandakumar
You need to convert your .sqlite database to .db inorder to fit to Android.
您需要将 .sqlite 数据库转换为 .db 以适应 Android。
On your app's first launch after installation
在您的应用安装后首次启动时
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);
On subsequent launches
在后续发布中
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);
Simply fire SQL queries
只需触发 SQL 查询
database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");
Get results on Array in CSV, JSON, XML
获取 CSV、JSON、XML 格式的数组结果
ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
{
//Do stuffs with each row
}
You need to include my library for this. Documentations here:
https://github.com/sangeethnandakumar/TestTube
为此,您需要包含我的库。文档在这里:https:
//github.com/sangeethnandakumar/TestTube
回答by craned
You will want to try android sqlite asset helper. It made opening a pre-existing db a piece of cake for me.
您将想要尝试android sqlite 资产助手。它使打开一个预先存在的数据库对我来说是小菜一碟。
I literally had it working in about a half hour after spending 3 hours trying to do it all manually. Funny thing is, I thought I was doing the same thing the library did for me, but something was missing!
在花了 3 个小时尝试手动完成所有工作后,我实际上让它在大约半小时内工作。有趣的是,我以为我在做图书馆为我做的同样的事情,但缺少了一些东西!
回答by Jakir Hossain
You can only read database from asset folder as the resources folders are read-only. If you need to do more operation like create, update, delete you can do a tricks. Copy the database from assets folder to storage and then you can do anything you want.
您只能从资产文件夹读取数据库,因为资源文件夹是只读的。如果你需要做更多的操作,比如创建、更新、删除,你可以做一个技巧。将数据库从资产文件夹复制到存储,然后你可以做任何你想做的事情。
Here is a quick example of Working with Android Pre Built Database.
这是使用 Android 预建数据库的快速示例。
There is a easy to use library too for accessing database from assets folder. You can check Android SQLiteAssetHelper (https://github.com/jgilfelt/android-sqlite-asset-helper). Good luck!
还有一个易于使用的库,用于从资产文件夹访问数据库。您可以查看 Android SQLiteAssetHelper ( https://github.com/jgilfelt/android-sqlite-asset-helper)。祝你好运!
回答by franklins
If you are planning to create a new SQLite database then over ride and implement the onCreate() Method as shown in the tutorial.
如果您打算创建一个新的 SQLite 数据库,那么请按照教程中所示的方法重写并实现 onCreate() 方法。
But if you are using a SQLite database that is created by another external source and you are going to pull it down, then leave the onCreate() method empty.
但是,如果您使用的是由另一个外部源创建的 SQLite 数据库,并且您打算将其拉下来,则将 onCreate() 方法留空。